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

Bru*_*ang 5 c++ utf-8 readfile chinese-locale

我正在编写一个网络爬虫来获取一些中文网络文件.获取的文件以utf-8编码.我需要读取这些文件来进行一些解析,例如提取URL和中文字符.但我发现当我将文件读入std :: string变量并将其输出到控制台时,中文字符变为垃圾字符.我将boost :: regex应用到std :: string变量中,并且可以提取除中文字符之外的所有URL.

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

PS我的CPP文件默认编码为ANSI,操作系统为Win8中文版;

Jig*_*ore 7

此代码可能有所帮助(它是使用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;
}
Run Code Online (Sandbox Code Playgroud)

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