为什么stream :: good是错误的示例? [英] Example of Why stream::good is Wrong?

查看:247
本文介绍了为什么stream :: good是错误的示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给了一个答案,我想通过循环这里检查流的有效性。

I gave an answer which I wanted to check the validity of stream each time through a loop here.

我的原始代码使用,看起来与此类似:

My original code used good and looked similar to this:

ifstream foo("foo.txt");

while (foo.good()){
    string bar;
    getline(foo, bar);
    cout << bar << endl;
}

我立即被指向这里,并告诉从不测试。显然这是我不明白的,但我想要正确地做我的文件I / O。

I was immediately pointed here and told to never test good. Clearly this is something I haven't understood but I want to be doing my file I/O correctly.

我用几个例子测试我的代码,不能好测试代码失败。

I tested my code out with several examples and couldn't make the good-testing code fail.

首先(正确打印,以一行结尾) p>

First (this printed correctly, ending with a new line):


bleck 1

blee 1 2

blah

以新的行


bleck 1
blee 1 2
blah
ends in new line

第二个(正确打印,以最后一行结尾):



Second (this printed correctly, ending in with the last line):


bleck 1

blee 1 2

blah

this doesn' t在新行中结束

bleck 1
blee 1 2
blah
this doesn't end in a new line

第三个是空文件(正确打印,单个换行符。)

Third was an empty file (this printed correctly, a single newline.)

第四个是缺少的文件(这个没有打印出来。)

Fourth was a missing file (this correctly printed nothing.)

有人可以帮我举一个例子, / em>

Can someone help me with an example that demonstrates why good-testing shouldn't be done?

推荐答案

他们错了。咒语是从不测试 .eof()'。

They were wrong. The mantra is 'never test .eof()'.

  • Why is iostream::eof inside a loop condition considered wrong?

即使那个咒语是舷外的,因为两者都有助于诊断提取失败后的流状态。

Even that mantra is overboard, because both are useful to diagnose the state of the stream after an extraction failed.

所以,口头禅应该更像


不要使用 good() eof()可检测eof,然后再尝试读取

Don't use good() or eof() to detect eof before you try to read any further

fail() >

Same for fail(), and bad()

当然,在使用流之前可以有用地使用 stream.good 已成功打开的文件流)

Of course stream.good can be usefully employed before using a stream (e.g. in case the stream is a filestream which has not been successfully opened)

但是,两者都非常非常经常滥用

However, both are very very very often abused to detect the end of input, and that's not how it works.

为什么不应该使用此方法的规范示例:

A canonical example of why you shouldn't use this method:

std::istringstream stream("a");
char ch;
if (stream >> ch) {
   std::cout << "At eof? " << std::boolalpha << stream.eof() << "\n";
   std::cout << "good? " << std::boolalpha << stream.good() << "\n";
}

列印

false
true

a href =http://coliru.stacked-crooked.com/a/e2eef88fdd223a37> Live On Coliru

See it Live On Coliru

这篇关于为什么stream :: good是错误的示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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