gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:29:29 24 4
gpt4 key购买 nike

我读过很多讨论这个问题的文章和论坛帖子,对于这样一个简单的任务,所有的解决方案似乎都太复杂了。

这是直接来自 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;
}

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

在 GNU/Linux 中,只需将文件保存为 UTF-8 格式即可。

在 Windows 中,这是行不通的。将文件转换为 UCS-2 Little Endian(Windows 似乎默认使用的格式)并将所有函数更改为对应的 wchar_t 也无法解决问题。

难道没有某种“正确”的方法可以在不进行各种神奇的编码转换的情况下完成这项工作吗?

最佳答案

Windows 控制台在某种程度上支持 unicode。它不支持从左到右和“复杂脚本”。要使用 Visual C++ 打印 UTF-16 文件,请使用以下命令:

   _setmode(_fileno(stdout), _O_U16TEXT);   

并使用wcout代替cout

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

有关控制台对 unicode 的支持的更多信息,请参阅 this blog

关于C++:将 Unicode 文件的内容输出到 Windows 中的控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4909187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com