为什么是(foobar>> x)优先于(!foobar.eof())

编程入门 行业动态 更新时间:2024-10-14 08:27:22
本文介绍了为什么是(foobar>> x)优先于(!foobar.eof())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: eof()不良做法?

我的老师说我们不应该使用EOF来读取文本文件或二进制文件信息,而是应该使用(afile >> x)。他没有解释为什么,有人可以解释给我。有人可以解释这两种不同的阅读方法有什么区别

My teacher said we shouldnt use EOF to read in text file or binary file information instead we should use (afile>>x). He didnt explain why, can someone explain to me. Can someone also explain what are the differences in this two different method of reading

//Assuming declaration //ifstream foobar ( ! foobar.eof() ) { foobar>>x; // This is discouraged by my teacher } while (foobar>>x) { //This is encouraged by my teacher }

推荐答案

operator>> 因为文件不在结尾,在尝试读取并且成功或失败之后,在之后返回对流的引用,并且流评估为 true if它成功或 false 如果失败。测试 eof()首先意味着该文件可以没有有用的数据,但是没有在EOF,然后当你从它读取,它在EOF和阅读

operator>> returns a reference to the stream in the state it is after the read has been attempted and either succeeded or failed, and the stream evaluates to true if it succeeded or false if it failed. Testing for eof() first means that the file can have no useful data in it but not be at EOF yet, then when you read from it, it's at EOF and the read fails.

另一个重要的细节是 operator>> for streams skips all leading 空格,而不是尾部空格。这是为什么文件在读取之前不能处于EOF,并且在读取之后处于EOF。

Another important detail is that operator>> for streams skips all leading whitespace, not trailing whitespace. This is why a file can not be at EOF before the read and be at EOF after a read.

此外,当文件中的下一个数据是数据时,不能读取为整数(例如,下一个数据 x ),而不仅仅是在EOF时,这是非常重要的。

Additionally, the former works when the next data in the file is data that cannot be read into an integer (for example, the next data is x), not just when it's at EOF, which is very important.

示例:

考虑代码:

int x, y; f >> x; if (!f.eof()) f >> y;

假设 f 数据123␣(␣表示空格),第一次读取将成功,但之后文件中没有更多的整数,并且不是 在EOF。第二次读取将失败,文件将在EOF,但你不知道,因为你测试EOF之前,你尝试阅读。然后你的代码继续导致未定义的行为,因为 y 未初始化。

Assuming f is a file that contains the data 123␣ (the ␣ means space), the first read will succeed, but afterwards the file has no more integers in it and it is not at EOF. The second read will fail and the file will be at EOF, but you don't know because you tested for EOF before you tried reading. Then your code goes on to cause undefined behaviour because y is uninitialised.

更多推荐

为什么是(foobar>> x)优先于(!foobar.eof())

本文发布于:2023-11-29 11:23:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为什么是   foobar   amp   gt   eof

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!