从文件中读取.txt字符串无法正确打印,但是当写回文件时,它很好
wstring read from .txt file doesn't print properly, but when written back to a file it's fine
我正在用一段时间从.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.:很抱歉我的英语不好
相关文章:
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 很好的语法来获取对向量/数组数据的大小引用?
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 尽管一切看起来都很好,但值不会交换
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 在 C++11 中利用 int*_t、int_fast*_t 和 int_least*_t 之间的差异的一个很好的例子是
- 有没有办法关闭文件? fclose 不能很好地工作
- 为许多类可能需要的所有常量变量制作独立的头文件是否是一种很好的做法?
- 简单的文本文件格式化在linux下崩溃,但在Windows中很好
- fstream 没有打开文件,尽管一切看起来都很好
- 从文件中读取.txt字符串无法正确打印,但是当写回文件时,它很好
- 为什么我的.exe文件崩溃了,但在调试和发布版本中工作得很好
- C++,如果其他新文件出现问题,使用g++进行编译可以很好地工作
- cpp文件不使用cl编译,但在Visual Studio中编译得很好
- g++可以很好地链接带有旧代码的旧对象文件
- 为什么设置故障位.文件似乎打印得很好
- md5的实现在字符串上工作得很好,但是在文件上不能给出正确的结果
- 文件夹结构-很好的实践
- 一个很好的性能替代PHP-字符串/文件操作
- 在哪里找到一个很好的指令如何解析一个c++头文件