eof() 不好的做法?
可能的重复:
为什么循环条件内的 iostream::eof 被认为是错误的?< /a>
所以我一直在很多需要文件输入的程序中使用 eof()
函数,我的教授说使用它很好,但是有一些人这么说我不应该在没有真正说明原因的情况下使用它。所以我想知道,有充分的理由吗?
Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
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.Wrong:
Correct:
你不应该使用它,因为如果由于其他原因输入失败,你可能会被搞砸。
如果文件的内容是“WHAARRRRRRGARBL”,上面的循环中会发生什么?它无限循环,因为它不是文件的末尾,但你仍然无法从中提取 int 。
You shouldn't use it because if input fails for another reason, you can be screwed.
What happens in the above loop if the contents of file are "WHAARRRRRRGARBL"? It loops infinitely, because it's not the end of the file, but you still can't extract an int from it.
你用得怎么样?
.eof()
会告诉您流已经到达文件末尾,它已尝试读取不存在的数据。这通常不是您想要的。通常,您想知道正在到达文件末尾,或者即将到达文件末尾,而不是已经到达文件末尾。在这样的循环中:
您将尝试读取输入并失败,然后您将执行
/* do stuff */
中的所有内容,然后循环条件失败并且循环停止。该循环的另一个问题是输入可能会通过其他方式失败。如果文件中存在非 EOF 的错误条件,
.fail()
将返回true
,但.eof()
不会。How are you using it? What
.eof()
will tell you is that the stream has already hit the end of file, that it has tried to read data that isn't there.This isn't usually what you want. Usually, you want to know that you are hitting the end of file, or that you are about to hit the end of file, and not that you have already hit it. In a loop like:
you are going to attempt to read input in and fail, and then you are going to execute everything in
/* do stuff */
, and then the loop condition fails and the loop stops.Another problem with that loop is that there's other ways input can fail. If there's an error condition on the file that isn't EOF,
.fail()
will returntrue
but.eof()
won't.如果上面的答案令人困惑:
人们认为它所做的是错误的:
它实际上做了什么:
如果 eof() 为 true,那么您就已经犯了一个错误。这就解释了教授的说法。按其含义使用它,发生了错误。
In case the above answers are confusing:
What people thinks it does is wrong:
What it actually does:
If eof() is true, you've already made a mistake. Thus explains the professors statement. Use it for what it means, an error has occurred.