string,wstring,cout,wcout 与中文字符的输入输出

c++中,可以直接利用string及cout进行中文的存储及输出:


[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. void main()  
  6. {  
  7.     string s1="第一";  
  8.     cout<<s1<<endl;   
  9. }  

正常输出:

第一

但是有些时候不得不用到wstring来存储中文字符,这时输出需要

  • 导入locale头文件
  • 中文字符前需要加L,并用wstring存储
  • 输出前更改本地语言,wcout.imbue(locale("chs"))
  • 用wcout输出

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <locale>  
  4. using namespace std;  
  5.   
  6. void main()  
  7. {  
  8.     string s1="第一";  
  9.     wstring s2=L"第二";  
  10.     cout<<s1<<endl;  
  11.     wcout.imbue(locale("chs"));  
  12.     wcout<<s2<<endl;  
  13. }  

结果便是:

第一

第二

你可能感兴趣的:(string,wstring,cout,wcout 与中文字符的输入输出)