c++ - UTF-8 与 cpp 案例所需的解释

标签 c++ visual-studio utf-8

我在 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

这背后的解释是什么?我可以通过某种方式让 coutprintf 一样工作吗?

附件

许多人说 Windows 控制台根本不支持 UTF-8 字符。我是匈牙利人,我的 Windows 设置为英语(日期格式除外,它们设置为匈牙利语)并且西里尔字母仍然与匈牙利字母一起正确显示:

Hungarian and Cyrillic letters on console at the same time

(我的默认控制台代码页是 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/

相关文章:

c++ - 计算 gluLookAt、glOrtho 和 glFrustum

c++ - 调用 vkCreateInstance() 时出现奇怪的错误

c++ - 闪屏上的图像 C++ (Windows)

visual-studio - Visual Studio 2008 Post Build 事件——仅在重建时运行

java - UTF-8 的字符串构造函数是否已损坏?

java - 为什么阿拉伯字母没有插入数据库?

c++ - 将 stringstream 换成 cout

c++ - 如何在 OpenCV 中将点传递给 cvFitEllipse2

visual-studio - 带有使用多个值的生成器表达式的 CMake set_property 命令

javascript - Webpack 错误 : You may need an appropriate loader to handle this file type. | @字符集 "UTF-8";