C++ 使用wstring获取行读取文件
我有一个包含文本的文件,我想将此文件中的每一行都放入一个C++ 使用wstring获取行读取文件,c++,string,ifstream,wstring,C++,String,Ifstream,Wstring,我有一个包含文本的文件,我想将此文件中的每一行都放入一个std::wstring变量。如果这样做,我会得到一个错误,那么是否可以使用std::wstring或者我必须使用std::string?这是我的代码: std::ifstream fichier( "text.txt" ); if ( fichier ) { std::wstring ligne; while ( std::getline( fichier, ligne ) ) { //work with li
std::wstring
变量。如果这样做,我会得到一个错误,那么是否可以使用std::wstring
或者我必须使用std::string
?这是我的代码:
std::ifstream fichier( "text.txt" );
if ( fichier )
{
std::wstring ligne;
while ( std::getline( fichier, ligne ) )
{
//work with ligne
}
}
如前所述,如果我用
std::string
替换std::wstring
,我没有错误。尝试使用std::wifstream
而不是std::ifstream来使用wstring读取文件,我发现wifstream
效果非常好,即使在visual studio调试器中正确显示UTF-8字(我在读繁体中文),来自:
#包括
#包括
#包括
std::wstring读取文件(常量字符*文件名)
{
std::wifstream wif(文件名);
imbue(std::locale(std::locale::empty(),新std::codevt_utf8));
std::wstringstream wss;
wss
#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();
}
// usage
std::wstring wstr2;
wstr2 = readFile("C:\\yourUtf8File.txt");
wcout << wstr2;