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

查看:94
本文介绍了为什么(foobar>> x)优于(!foobar.eof())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么在循环条件内的iostream :: eof被认为是错误的?
eof()不良做法?

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

//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如果失败.首先测试eof()意味着该文件中尚没有有用的数据,但是还没有到达EOF,然后当您从文件中读取文件时,它处于EOF且读取失败.

另一个重要的细节是,流的operator>>会跳过所有前导空格,而不是尾随空白.这就是为什么文件在读取前不能处于EOF且在读取后不能处于EOF的原因.

此外,前者适用于文件中的下一个数据是无法读取为整数的数据(例如,下一个数据为x),而不仅仅是在EOF时,这非常重要./p>

示例:

考虑代码:

int x, y;

f >> x;

if (!f.eof())
    f >> y;

假设f是一个包含数据123␣的文件(␣表示空格),则第一次读取将成功,但是此后文件中没有更多的整数,并且 not 在EOF.第二次读取将失败,并且文件将位于EOF,但是您不知道,因为在尝试读取之前已经测试了EOF.然后,您的代码会继续导致未定义的行为,因为y未初始化.

Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?
eof() bad practice?

My teacher said we shouldn't use EOF to read in text file or binary file information instead we should use (afile>>x). He didn't 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

}

解决方案

Because the file is not at the end before you try to read from it.

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.

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.

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.

Example:

Consider the code:

int x, y;

f >> x;

if (!f.eof())
    f >> 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天全站免登陆