我在 Windows 7 64 位上安装了 Microsoft Visual Studio 2010。 (在项目属性中,“字符集”设置为“未设置”,但是每个设置都会导致相同的输出。)
源代码:
using namespace std;
char const charTest[] = "árvíztűrő tükörfúrógép ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP\n";
cout << charTest;
printf(charTest);
if(set_codepage()) // SetConsoleOutputCP(CP_UTF8); // *1
cerr << "DEBUG: set_codepage(): OK" << endl;
else
cerr << "DEBUG: set_codepage(): FAIL" << endl;
cout << charTest;
printf(charTest);
*1:包含 windows.h
会把事情搞砸,所以我从一个单独的 cpp 中包含它。
编译后的二进制文件包含作为正确 UTF-8 字节序列的字符串。如果我使用 chcp 65001
将控制台设置为 UTF-8 并发出 type main.cpp
,字符串将正确显示。
测试(控制台设置为使用 Lucida Console 字体):
D:\dev\user\geometry\Debug>chcp
Active code page: 852
D:\dev\user\geometry\Debug>listProcessing.exe
├írv├şzt┼▒r┼Ĺ t├╝k├Ârf├║r├│g├ęp ├üRV├ŹZT┼░R┼É T├ťK├ľRF├ÜR├ôG├ëP
├írv├şzt┼▒r┼Ĺ t├╝k├Ârf├║r├│g├ęp ├üRV├ŹZT┼░R┼É T├ťK├ľRF├ÜR├ôG├ëP
DEBUG: set_codepage(): OK
��rv��zt��r�� t��k��rf��r��g��p ��RV��ZT��R�� T��K��RF��R��G��P
árvíztűrő tükörfúrógép ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP
这背后的解释是什么?我可以通过某种方式让 cout
像 printf
一样工作吗?
附件
许多人说 Windows 控制台根本不支持 UTF-8 字符。我是匈牙利人,我的 Windows 设置为英语(日期格式除外,它们设置为匈牙利语)并且西里尔字母仍然与匈牙利字母一起正确显示:
(我的默认控制台代码页是 CP852)
最佳答案
这里的区别在于 C++ 运行时和 C 库处理系统区域设置的方式。
要使用 std::cout 获得相同的结果,您可以尝试 std::ios::imbue方法和std::locale
但 utf-8 和 C++ 的主要问题描述了 here
C++03 offers two kinds of string literals. The first kind, contained within double quotes, produces a null-terminated array of type const char. The second kind, defined as L"", produces a null-terminated array of type const wchar_t, where wchar_t is a wide-character. Neither literal type offers support for string literals with UTF-8, UTF-16, or any other kind of Unicode encodings.
所以无论如何它都是特定于实现的,因此不可移植,因为标准 C++ 输出流都不能理解 utf-8。
关于c++ - UTF-8 与 cpp 案例所需的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12545252/