今天碰到了从控制台输出宽字符的问题:
演示代码:
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
CHAR*pCstr = "这是char字符串1";
CHARCStr[] = "这是char字符串2";
WCHAR*pWStr = L"这是wchar字符串1";
WCHARWStr[] = L"这是wchar字符串2";
//两种方式输出第一组字符串
cout<< pCstr << endl;
cout<< CStr << endl;
wcout<< pCstr << endl;
wcout<< CStr << endl;
//wcout.imbue(locale("chs"));
//两种方式输出第二组字符串
cout<< pWStr << endl;
cout<< WStr << endl;
wcout << pWStr << endl;
wcout<< WStr << endl;
return0;
}
程序输出:
看下上面四个字符串在内存里的数据:
D5 E2 CA C7是“这是的编码”,63 68 61 72是“char”的编码。开始我以为是UTF-8.用010各种显示却不是。网上说是ANSI编码。
这个跟上面一样。有没有发现用指针形式定义的字符串藏在数据段,而用数组形式定义的字符串藏在堆栈里头。
Unicode编码.
综上可以得出结论:
char类型的字符串只能用cout输出,不能用wcout输出。Wcout会输出它的地址。
Wcout默认情况下也不能输出带有中文的字符串。解决的办法是在输出前加上一条语句:
wcout.imbue(locale("chs"));
这条语句的作用是让wcout支持输出简体中文。
Imbue 函数:
函数原型: locale basic_ios::imbue( const locale& loc);
参数说明: loc: const对象引用,表示输出时,使用的区域语言对象
返回值: 之前的使用的区域语言
示例:
#include <iostream>
using namespace std;
int main()
{
wcout.imbue(locale("chs"));//使用中文区域语言
wcout<<L"English中文"<<endl;
return 0;
}