C++:在Windows中将Unicode文件的内容输出到控制台

Nik*_*lai 6 c++ windows unicode console

我已经阅读了一堆文章和论坛帖子讨论这个问题所有的解决方案似乎太复杂了这么简单的任务.

以下是来自cplusplus.com的示例代码:

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

只要example.txt只有ASCII字符,它就可以正常工作.如果我试图用俄语添加一些东西,事情会变得混乱.

在GNU/Linux中,它就像将文件保存为UTF-8一样简单.

在Windows中,这不起作用.将文件转换为UCS-2 Little Endian(默认情况下Windows似乎使用)并将所有函数更改为wchar_t对应文件也不起作用.

如果没有进行各种魔术编码转换,是不是有某种"正确"的方法来完成这项工作?

Joh*_*ohn 6

Windows控制台支持unicode.它不支持从左到右和"复杂脚本".要使用Visual C++打印UTF-16文件,请使用以下命令:

   _setmode(_fileno(stdout), _O_U16TEXT);   
Run Code Online (Sandbox Code Playgroud)

并使用wcout而不是cout.

不支持"UTF8"代码页,因此对于UTF-8,您必须使用 MultiBytetoWideChar

有关unicode的控制台支持的更多信息,请参阅此博客


Mar*_*wis 2

使用 cout 输出到 Windows 控制台的正确方法是首先调用GetConsoleOutputCP,然后将输入转换为控制台代码页。或者,使用WriteConsoleW,传递wchar_t*.