gpt4 book ai didi

c++ - 如何读取包含汉字的UTF-8编码文件并在控制台正确输出?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:18 27 4
gpt4 key购买 nike

我正在编写一个网络爬虫来获取一些中文网络文件。获取的文件以 utf-8 编码。我需要读取这些文件来做一些解析,比如提取 URL 和汉字。但是我发现当我把文件读入一个std::string变量并输出到控制台时,汉字变成了乱码。我将 boost::regex 应用到 std::string 变量中,可以提取除中文字符之外的所有 URL。

我怎样才能解决这些问题?

附言我的CPP文件默认编码为ANSI,操作系统是中文Win8;

最佳答案

此代码可能有帮助(它是用 VC++ 2010 编译的)。我用一个包含非拉丁字符的 UTF-8 文件对其进行了测试,它似乎可以工作,但我不知道它是否适用于中文字符。查看以下链接以获取更多信息:_setmodecodecvt_utf8 .

#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <codecvt>
#include <fcntl.h>
#include <io.h>

using namespace std; // Sorry for this!

void read_all_lines(const wchar_t *filename)
{
wifstream wifs;
wstring txtline;
int c = 0;

wifs.open(filename);
if(!wifs.is_open())
{
wcerr << L"Unable to open file" << endl;
return;
}
// We are going to read an UTF-8 file
wifs.imbue(locale(wifs.getloc(), new codecvt_utf8<wchar_t, 0x10ffff, consume_header>()));
while(getline(wifs, txtline))
wcout << ++c << L'\t' << txtline << L'\n';
wcout << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
// Console output will be UTF-16 characters
_setmode(_fileno(stdout), _O_U16TEXT);
if(argc < 2)
{
wcerr << L"Filename expected!" << endl;
return 1;
}
read_all_lines(argv[1]);
return 0;
}

如果中文字符看起来不像预期的那样,请确保控制台使用的字体支持 UTF-16(即不要使用位图字体)。

关于c++ - 如何读取包含汉字的UTF-8编码文件并在控制台正确输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20195262/

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