wstring和string区别

在中国,wstring的存在主要是因为有汉字。

       
       
       
       
  1. typedef basic_string< char, char_traits< char>, allocator< char> >
  2. string;
  3. typedef basic_string< wchar_t, char_traits< wchar_t>, allocator< wchar_t> >
  4. wstring;
差异就在char还是wchar_t


       
       
       
       
  1. #ifndef _WCHAR_T_DEFINED
  2. typedef unsigned short wchar_t;
  3. #define _WCHAR_T_DEFINED
  4. #endif
所以wchar_t本质上是一个unsigned short,2个字节的大小,即16bit

窄字符,一般用于满足ASCII编码,一个单元一个char
宽字符,一般用于满足UNICODE编码,一个单元两个char

也就是说,宽字符,每表示一个字符其实是占了16bit,即2个char的大小。而汉字就是需要16bit来表示。

下面是测试例子:

       
       
       
       
  1. string s = "你好!";
  2. cout << s[ 1] << endl;
你以为输出的是“好”,其实是乱码。输出好的正确方式如下

       
       
       
       
  1. string s = "你好!";
  2. cout << s[ 2] << s[ 3] << endl;
如果使用wstring,则可以像string一样来输出汉字了

       
       
       
       
  1. wcout.imbue( std::locale( "chs"));
  2. wstring ws = L"你好!";
  3. wcout << ws[ 1] << endl;



你可能感兴趣的:(C/C++)