c++ - 为什么在循环条件(即 `while (!stream.eof())`)内的iostream::eof被认为是错误的?

标签 c++ iostream c++-faq

我刚刚在this答案中找到一条评论,说在循环条件下使用iostream::eof是“几乎肯定是错误的”。我通常使用类似while(cin>>n)的东西-我猜它隐式检查EOF。

为什么显式使用while (!cin.eof())检查eof是错误的?

与在C语言中使用scanf("...",...)!=EOF有什么不同(我经常会毫无问题地使用它)?

最佳答案

因为iostream::eof仅在读取流的末尾后才返回true。它并不表示下次读取将是流的结尾。

考虑一下(假设下一个读取将在流的末尾):

while(!inStream.eof()){
  int data;
  // yay, not end of stream yet, now read ...
  inStream >> data;
  // oh crap, now we read the end and *only* now the eof bit will be set (as well as the fail bit)
  // do stuff with (now uninitialized) data
}

反对:
int data;
while(inStream >> data){
  // when we land here, we can be sure that the read was successful.
  // if it wasn't, the returned stream from operator>> would be converted to false
  // and the loop wouldn't even be entered
  // do stuff with correctly initialized data (hopefully)
}

关于第二个问题:
if(scanf("...",...)!=EOF)

是相同的
if(!(inStream >> data).eof())

不是
if(!inStream.eof())
    inFile >> data

关于c++ - 为什么在循环条件(即 `while (!stream.eof())`)内的iostream::eof被认为是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58917521/

相关文章:

c++ - 正确替换 C++ 中缺失的 'finally'

java - 为什么 Java 没有像 C++ 中那样的初始化列表?

c++ - cin.getline() 正在删除我在 C++ 中输入的第一个让步

c++ - 在c++中创建一个函数以输出到指定的源

c++ - 为什么#define 不好?

c++ - 如何使用 program.exe < text.txt 使用 C++ 读取输入

c++ - 为什么结构体的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 为什么必须在何处以及为什么要放置"template"和"typename"关键字?

C++: C1083: 'afxwin.h' : 没有这样的文件或目录 - VS2010 with VC6 daffodil

c++ - Dependency Walker 在函数名称后显示 @x