#include <iostream>
#include <fstream>
int main() {
std::fstream inf( "ex.txt", std::ios::in );
while( !inf.eof() ) {
std::cout << inf.get() << "\n";
}
inf.close();
inf.clear();
inf.open( "ex.txt", std::ios::in );
char c;
while( inf >> c ) {
std::cout << c << "\n";
}
return 0;
}
我真的对 eof()
函数感到困惑。假设我 ex.txt 的内容是:
abc
在使用 eof()
读取时,它总是读取一个额外的字符并显示 -1
。但是 inf >> c
给出了正确的输出,即“abc”?谁能帮我解释一下?
最佳答案
-1 是 get
表示您已到达文件末尾。使用 std::char_traits<char>::eof()
进行比较(或 std::istream::traits_type::eof()
) - 避免 -1,这是一个神奇的数字。 (虽然另一个有点冗长 - 你可以随时调用 istream::eof
)
只有在读取尝试读取文件末尾时,才会设置 EOF 标志。如果我有一个 3 字节的文件,而我只读取了 3 个字节,EOF 是 false
,因为我还没有尝试读过文件的末尾。虽然这对于通常知道其大小的文件来说似乎令人困惑,但直到在某些设备(例如管道和网络套接字)上尝试读取时才知道 EOF。
第二个例子是 inf >> foo
将始终返回 inf
, 具有尝试读取某些内容并将其存储在 foo
中的副作用. inf
, 在 if
或 while
, 将计算为 true
如果文件“好”:没有错误,没有 EOF。因此,当读取失败时,inf
评估为 false
,并且您的循环正确中止。但是,请采取以下常见错误:
while(!inf.eof()) // EOF is false here
{
inf >> x; // read fails, EOF becomes true, x is not set
// use x // we use x, despite our read failing.
}
但是,这个:
while(inf >> x) // Attempt read into x, return false if it fails
{
// will only be entered if read succeeded.
}
这是我们想要的。
关于c++ - ifstream 的 eof() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4533063/