我试图找出在 c++ 中处理 unicode 的正确方法。我想了解 g++ 如何处理文字宽字符串以及包含 unicode 字符的常规 c 字符串。我已经设置了一些基本测试,但并不真正了解发生了什么。
wstring ws1(L"«¬.txt"); // these first 2 characters correspond to 0xAB, 0xAC
string s1("«¬.txt");
ifstream in_file( s1.c_str() );
// wifstream in_file( s1.c_str() ); // this throws an exception when I
// call in_file >> s;
string s;
in_file >> s; // s now contains «¬
wstring ws = textToWide(s);
wcout << ws << endl; // these two lines work independently of each other,
// but combining them makes the second one print incorrectly
cout << s << endl;
printf( "%s", s.c_str() ); // same case here, these work independently of one another,
// but calling one after the other makes the second call
// print incorrectly
wprintf( L"%s", ws.c_str() );
wstring textToWide(string s)
{
mbstate_t mbstate;
char *cc = new char[s.length() + 1];
strcpy(cc, s.c_str());
cc[s.length()] = 0;
size_t numbytes = mbsrtowcs(0, (const char **)&cc, 0, &mbstate);
wchar_t *buff = new wchar_t[numbytes + 1];
mbsrtowcs(buff, (const char **)&cc, numbytes + 1, &mbstate);
wstring ws = buff;
delete [] cc;
delete [] buff;
return ws;
}
似乎对 wcout 和 wprintf 的调用以某种方式破坏了流,并且只要字符串被编码为 utf-8,调用 cout 和 printf 总是安全的。
处理 unicode 的最佳方法是在处理之前将所有输入转换为宽,然后在发送到输出之前将所有输出转换为 utf-8?