eof()坏实践? [英] eof() bad practice?
本文介绍了eof()坏实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在许多需要文件输入的程序中使用了 eof()
函数,我的教授说这是很好使用,但一些人说SO我不应该使用它没有真正具体说明的原因。
So I've been using the eof()
function in a lot of my programs that require file input, and my professor said that it is fine to use but a few people on SO have said that I shouldn't use it without really specifying the reason. So I was wondering, is there a good reason?
推荐答案
您可以使用 eof
来测试报告的确切条件 - 无论您是否尝试读取过去的文件结尾。您不能使用它来测试是否有更多要读取的输入,或者阅读是否成功,这是更常见的测试。
You can use eof
to test for the exact condition it reports - whether you have attempted to read past end of file. You cannot use it to test whether there's more input to read, or whether reading succeeded, which are more common tests.
错误:
while (!cin.eof()) {
cin >> foo;
}
正确:
if (!(cin >> foo)) {
if (cin.eof()) {
cout << "read failed due to EOF\n";
} else {
cout << "read failed due to something other than EOF\n";
}
}
这篇关于eof()坏实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文