我刚刚在答案中发现了一条评论,说iostream::eof在循环条件中使用“几乎肯定是错误的”。我通常使用类似的东西while(cin>>n)- 我猜它会隐式检查 EOF。
iostream::eof
while(cin>>n)
为什么检查 eof 显式使用while (!cin.eof())错误?
while (!cin.eof())
它与scanf("...",...)!=EOF在 C 中使用(我经常毫无问题地使用)有什么不同?
scanf("...",...)!=EOF
因为iostream::eof只会在读取流的末尾true 后返回。 它并不 表示 下一次读取将是流的结尾。
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