从文件中读取.txt字符串无法正确打印,但是当写回文件时,它很好

wstring read from .txt file doesn't print properly, but when written back to a file it's fine

本文关键字:文件 很好 打印 写回 txt 读取 字符串      更新时间:2023-10-16

我正在用一段时间从.txt文件中读取一个wstring!eof循环:

std::wifstream fileStream(path);
std::wstring input;
while (fileStream.eof() == false) {
getline(fileStream, input);
text += input + L'n';
}

但当我把它打印出来时,一些字符会变成其他字符。到目前为止,č已经转换为e(带有向后逗号ontop),Ş转换为i(带有向后的逗号ntop),š转换为错误字符。首先我怀疑是格式问题。但是当我把字符串写入一个新的.txt文件时,它就完全没问题了。

此外,我正在使用_setmode(_fileno(stdout), _O_U8TEXT);让wcout甚至工作。

通过读取二进制文件,然后使用win32api:中的MultiByteToWideChar函数转换为wstring来解决

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 (fileStream.eof() == false) {
getline(fileStream, input);
text += input + L'n';
}

因为filestream.eof()false,所以您在最后一行读了两次,直到您试图读过最后一行。

我建议你用

while ( getline(fileStream, input) )
text += input + L'n';

p.s.:很抱歉我的英语不好