为什么是(foobar>> x)优先于(!foobar.eof()) [英] Why is (foobar>>x) prefered over (! foobar.eof() )

查看:135
本文介绍了为什么是(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())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆