c++和g++如何处理unicode
How do c++ and g++ deal with unicode?
我正试图找出在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的最佳方法是在处理之前将所有输入转换为wide,在发送到outupt之前将所有输出转换为utf-8吗?
处理Unicode最全面的方法是使用Unicode库,如ICU。Unicode比一堆编码有更多的方面。C++不提供API来处理这些额外的方面。重症监护室确实如此。
如果您只想处理编码,那么一种可行的方法是正确使用内置的C++方法。这包括呼叫
std::setlocale(LC_ALL,
/*some system-specific locale name, probably */ "en_US.UTF-8")
在节目的开头。此外,不在同一程序中使用cout
/printf
和wcout
/wprintf
。(您可以在同一程序中使用标准句柄以外的常规和宽流对象)。
将所有输入转换为wide并将所有输出转换为utf-8是一种合理的策略。使用utf-8也是合理的。这在很大程度上取决于你的申请。C++11具有内置的UTF8、UTF16和UTF32字符串类型,这在一定程度上简化了任务。
无论您做什么,都不要在字符串文字中使用扩展字符集的元素。(在C++11中,可以在UTF8/16/32字符串文字中使用它们)。
相关文章:
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- ascii 和 unicode 在处理级别有什么区别吗?
- 用wchar_t处理 unicode 字符好吗?它不会引起任何问题吗?
- 在2018年使用C++处理Unicode的正确方法是什么?
- C++ 将 setmode 与 _O_U8TEXT 一起使用来处理 unicode 时崩溃
- 使用C 17处理Unicode的有效,符合标准的机制是什么
- 如何处理C 中Unicode支持涉及的代码重复
- 如何处理JSON字符串中的unicode值
- C++中的Unicode字符串处理
- 显式使用Unicode/ANSI Windows API和让它们由别名处理之间的区别
- 如何使用Unicode处理PCRE
- 如何在Visual Studio中处理Unicode和非Unicode项目的混合
- c++和g++如何处理unicode
- 在C++中处理 Unicode 字符
- visual如何在C++中处理Unicode字符
- 使用Windows API处理Unicode字符串
- 如何审核我的Windows应用程序以获得正确的Unicode处理