gpt4 book ai didi

c++ - Ifstream 在几行后停止读取文件

转载 作者:行者123 更新时间:2023-11-28 01:15:31 24 4
gpt4 key购买 nike

我在 stringstream 中使用 ifstream 来读取文件,但它在几行后停止...

string read(string filename)
{
ifstream inFile;
inFile.open(filename);
stringstream strStream;
strStream << inFile.rdbuf();
inFile.close();
string str = strStream.str();
return str;
}

这段代码在'zh¬'之后停止
我在想也许它们是 ascii 表中的控制字符,它停止后的第一个字符是 26。
但我认为这不重要。

最佳答案

您的 ifstream 正在以文本模式打开。尝试以二进制模式打开文件:std::ifstream inFile(文件名, std::ios::binary);

A text stream is an ordered sequence of characters composed into lines (zero or more characters plus a terminating '\n'). Whether the last line requires a terminating '\n' is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to the conventions for representing text in the OS (in particular, C streams on Windows OS convert \n to \r\n on output, and convert \r\n to \n on input)

  • Data read in from a text stream is guaranteed to compare equal to the data that were earlier written out to that stream only if all of the following is true:
    the data consist only of printing characters and the control characters \t and \n (in particular, on Windows OS, the character '\0x1A' terminates input)

  • no \n is immediately preceded by a space character (space characters that are written out immediately before a \n may disappear when read)

  • the last character is \n

A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream always equals to the data that were earlier written out to that stream. Implementations are only allowed to append a number of null characters to the end of the stream. A wide binary stream doesn't need to end in the initial shift state.

https://en.cppreference.com/w/cpp/io/c#Binary_and_text_modes

关于c++ - Ifstream 在几行后停止读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58855785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com