随着OS对中文的支持越来越理想,出现了新的编码,我们通过一个实例来了解string和wstring的一些差异吧。
V0.1版代码:
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string name1 = "Hello!";
wstring name2 = L"Hello!";
cout << name1 <<endl;
cout << "It's length is " << name1.length()<< endl;
wcout << name2 << endl;
wcout << "It's w_length is " << name2.length();
return 0;
}
显示结果:Hello!
It's length is 6
Hello!
It's w_length is 6
V0.2版代码,将name1和name2的初始值改为"你好“,即:
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string name1 = "你好!";
wstring name2 = L"你好!";
cout << name1 <<endl;
cout << "It's length is " << name1.length()<< endl;
wcout << name2 << endl;
wcout << "It's w_length is " << name2.length();
return 0;
}
显示结果:你好!
发现name2没有显示,应该是编码设置的问题,修改代码,在wcout之前,加一句语句:wcout.imbue ( locale("chs"));It's length is 5
现在正常了,显示结果:你好!
It's length is 5
你好!
It's w_length is 3
从这段代码可以看出:
1、中文字符在string类型中占2个位置,而在wstring中只占一个位置。
2、在用wcout输出中文字符前,需设置编码