C++读取UTF-8问题(使用<codecvt>)
问题来源于最近参加的一个比赛,要求输入输出必须为utf-8格式,而我因为运算速度的原因选择了使用C++作为编程语言,所以就面对了这个问题。目前这个问题还未完全解决,阶段性的记录这个过程。
查到的关于<codecvt>的方法来自于来源。
经过测试,该方法能够得到正确的字符串信息。
第一个示例
如下:
#include <sstream>
#include <fstream>
#include <codecvt>
std::wstring readFile(const char* filename)
{
std::wifstream wif(filename);
wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
std::wstringstream wss;
wss << wif.rdbuf();
return wss.str();
}
调用方式如下:
std::wstring wstr = readFile("a.txt");
暂时还没太搞明白这当中各个函数的作用。
第二个示例,复杂了一些
依旧是用<codecvt>,但是加入了<locale>
#include <locale>
#include <codecvt>
#include <string>
#include <fstream>
#include <cstdlib>
int main()
{
const std::locale empty_locale = std::locale::empty();
typedef std::codecvt_utf8<wchar_t> converter_type;
const converter_type* converter = new converter_type;
const std::locale utf8_locale = std::locale(empty_locale, converter);
std::wifstream stream(L"test.txt");
stream.imbue(utf8_locale);
std::wstring line;
std::getline(stream, line);
std::system("pause");
}
wstringstream的清空
和stringstream的清空一样,使用 .clear()函数和 .str("") 进行清空,只不过wstringstream的是 .str(L"")。参考清空std::stringstream,联系到stream的clear()和清空。
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <codecvt>
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char * argv[])
{
std::wstringstream stream;
wstring wstr;
while(1)
{
//clear(),这个名字让很多人想当然地认为它会清除流的内容。
//实际上,它并不清空任何内容,它只是重置了流的状态标志而已!
wstream.clear();
// 清空wstringstream的缓冲,每次循环内存消耗将不再增加!
stream.str(L"");
wstream<<L"sdfsdfdsfsadfsdafsdfsdgsdgsdgsadgdsgsdagasdgsdagsadgsdgsgdsagsadgs ";
wstream>>wstr;
}
system("PAUSE ");
return EXIT_SUCCESS;
}
接下来
接下来我应该会在这两个版本的基础上去尝试解析我的文件。
网友评论