我正在写一个网络爬虫来获取一些中文网页文件。获取的文件以utf-8编码。我需要读取这些文件来做一些解析,比如提取URL和中文字符。但我发现,当我将文件读入std::string变量并将其输出到控制台时,中文字符变成了垃圾字符。我将boost::regex应用到std::string变量中,可以提取除中文字符以外的所有URL。
我该如何解决这些问题呢?
P.S.我的CPP文件默认编码为ANSI码,操作系统为中文Win8;
发布于 2013-11-26 12:08:05
这段代码可能会有所帮助(它是用VC++ 2010编译的)。我用一个包含非拉丁字符的UTF-8文件测试了它,它似乎可以工作,但我不知道它是否能很好地处理中文字符。有关更多信息,请查看以下链接:_setmode和codecvt_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 (即。不要使用位图字体)。
发布于 2013-11-25 23:41:22
通常,使用w变体(wstring,wfstream,wcout),设置您的区域设置以匹配要求,在字符串文字的前面挂一个L。locale::global(locale(""))设置为匹配环境默认值,然后在未根据该默认设置运行的每个流上进行设置,例如,针对终端的区域设置的wcout.imbue(locale("Chinese_China.936")) might be Microsoft's name。这已经足够做我想做的事情了,希望它也能为你工作。
#include <iostream>
#include <locale>
using namespace std;
int main() {
locale::global(locale(""));
wstring word;
while (wcin >>word)
wcout<<word<<'\n';
wcout<<L"好運n";
}发布于 2013-11-25 23:58:47
如果需要正确显示字符,可以使用GNU中的libiconv。如果你只需要处理urls,std::string就可以了。问题出在windows控制台的代码页,而不是字符串本身。使用locale依赖于os和stdc++lib的实现,所以我不鼓励使用。
window的MultiByteToWideChar可能会有所帮助,但您需要检查MS的规范,了解这些函数如何对字符串执行转换。
https://stackoverflow.com/questions/20195262
复制相似问题