c++ - c++和g++如何处理unicode?

标签 c++ unicode g++

我正在尝试找出在 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 来处理任何这些额外方面。 ICU 有。

如果您只想处理编码,那么一种可行的方法是正确使用内置的 C++ 方法。这包括打电话

std::setlocale(LC_ALL, 
               /*some system-specific locale name, probably */ "en_US.UTF-8")

在程序的开头。此外,不要在同一程序中使用 cout/printfwcout/wprintf。 (您可以在同一程序中使用标准句柄以外的常规和宽流对象)。

将所有输入转换为 wide 并将所有输出转换为 utf-8 是一种合理的策略。使用 utf-8 也是合理的。很大程度上取决于您的应用程序。 C++11 具有内置的 UTF8、UTF16 和 UTF32 字符串类型,可以在一定程度上简化任务。

无论您做什么,都不要在字符串文字中使用扩展字符集的元素。 (在 C++11 中,可以在 UTF8/16/32 字符串文字中使用它们)。

关于c++ - c++和g++如何处理unicode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18319411/

相关文章:

c++ - C++字符串:size_t和字符串::npos

c++ - 存储递归函数的堆栈有多大。我应该考虑操作系统、编译器和硬件等哪些因素

c++ - 对符号 'XF86VidModeQueryExtension' 的 undefined reference (linux、qt creator IDE)

c++ - QMutexLocker : "QMutex pointer is misaligned", 中的 QThread ASSERT 失败

c++ - 错误 C4430 缺少类型说明符 - 假定为 int。注意 : C++ does not support default-int Generator

c++ - 请为我解释这个 Bresenham Line 绘图代码

delphi - 如何在TChart标签中显示Unicode

windows - 有没有办法在Windows键盘驱动程序中模拟箭头键?

python - Python 中图像中文本的 Unicode 问题

c++ - g++ 编译器忽略 const 返回类型