从 .txt 文件中读取的 wstring 打印不正确,但是当写回文件时没问题
wstring read from .txt file doesn't print properly, but when written back to a file it's fine
我正在使用 while !eof 循环从 .txt 文件读取 wstring:
std::wifstream fileStream(path);
std::wstring input;
while (fileStream.eof() == false) {
getline(fileStream, input);
text += input + L'\n';
}
但是当我在 wcout 中打印它时,一些字符会变成其他字符。到目前为止 č 已经变成了 e(上面有一个反逗号),ě 变成了 i(上面有一个反面逗号),而 š 变成了一个错误字符。首先我怀疑是格式问题。但是当我将字符串写入新的 .txt 文件时,它完全没问题。
我也在使用 _setmode(_fileno(stdout), _O_U8TEXT);
让 wcout 正常工作。
我不知道这是否是您遇到问题的原因,但是...
如果你写
while (fileStream.eof() == false) {
getline(fileStream, input);
text += input + L'\n';
}
你读了最后一行两次,因为 filestream.eof()
是 false
,直到你尝试读完最后一行。
我建议你像
while ( getline(fileStream, input) )
text += input + L'\n';
p.s.: 对不起我的英语不好
解决方法是将文件读取为二进制文件,然后使用 win32 中的 MultiByteToWideChar 函数转换为 wstring api:
std::ifstream fileStream(path, std::ios::binary | std::ios::ate);
auto size = fileStream.tellg();
fileStream.seekg(0, std::ios::beg);
LPCCH memory = new CCHAR[size];
fileStream.read((char*)memory, size);
text.resize(size);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, memory, size, (LPWSTR)text.c_str(), text.length());
delete[] memory;
我正在使用 while !eof 循环从 .txt 文件读取 wstring:
std::wifstream fileStream(path);
std::wstring input;
while (fileStream.eof() == false) {
getline(fileStream, input);
text += input + L'\n';
}
但是当我在 wcout 中打印它时,一些字符会变成其他字符。到目前为止 č 已经变成了 e(上面有一个反逗号),ě 变成了 i(上面有一个反面逗号),而 š 变成了一个错误字符。首先我怀疑是格式问题。但是当我将字符串写入新的 .txt 文件时,它完全没问题。
我也在使用 _setmode(_fileno(stdout), _O_U8TEXT);
让 wcout 正常工作。
我不知道这是否是您遇到问题的原因,但是...
如果你写
while (fileStream.eof() == false) {
getline(fileStream, input);
text += input + L'\n';
}
你读了最后一行两次,因为 filestream.eof()
是 false
,直到你尝试读完最后一行。
我建议你像
while ( getline(fileStream, input) )
text += input + L'\n';
p.s.: 对不起我的英语不好
解决方法是将文件读取为二进制文件,然后使用 win32 中的 MultiByteToWideChar 函数转换为 wstring api:
std::ifstream fileStream(path, std::ios::binary | std::ios::ate);
auto size = fileStream.tellg();
fileStream.seekg(0, std::ios::beg);
LPCCH memory = new CCHAR[size];
fileStream.read((char*)memory, size);
text.resize(size);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, memory, size, (LPWSTR)text.c_str(), text.length());
delete[] memory;