在中国,wstring的存在主要是因为有汉字。
-
typedef basic_string<
char, char_traits<
char>, allocator<
char> >
-
string;
-
typedef basic_string<
wchar_t, char_traits<
wchar_t>, allocator<
wchar_t> >
-
wstring;
差异就在char还是wchar_t
-
#ifndef _WCHAR_T_DEFINED
-
typedef
unsigned
short
wchar_t;
-
#define _WCHAR_T_DEFINED
-
#endif
所以wchar_t本质上是一个unsigned short,2个字节的大小,即16bit
窄字符,一般用于满足ASCII编码,一个单元一个char
宽字符,一般用于满足UNICODE编码,一个单元两个char
也就是说,宽字符,每表示一个字符其实是占了16bit,即2个char的大小。而汉字就是需要16bit来表示。
下面是测试例子:
-
string s =
"你好!";
-
cout << s[
1] <<
endl;
你以为输出的是“好”,其实是乱码。输出好的正确方式如下
-
string s =
"你好!";
-
cout << s[
2] << s[
3] <<
endl;
如果使用wstring,则可以像string一样来输出汉字了
-
wcout.imbue(
std::locale(
"chs"));
-
wstring ws =
L"你好!";
-
wcout << ws[
1] <<
endl;