使用getline(),而不设置failbit [英] Use getline() without setting failbit

查看:299
本文介绍了使用getline(),而不设置failbit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 getline()读取有效文件,而不设置 failbit ?我想使用 failbit ,以便在输入文件不可读时生成异常。

Is it possible use getline() to read a valid file without setting failbit? I would like to use failbit so that an exception is generated if the input file is not readable.

代码总是输出 basic_ios :: clear 作为最后一行 - 即使指定了有效的输入。

The following code always outputs basic_ios::clear as the last line - even if a valid input is specified.

cc:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(int argc, char* argv[])
{
    ifstream inf;
    string line;

    inf.exceptions(ifstream::failbit);
    try {
        inf.open(argv[1]);
        while(getline(inf,line))
            cout << line << endl;
        inf.close();
    } catch(ifstream::failure e) {
        cout << e.what() << endl;
    }
}

input.txt:

input.txt:

the first line
the second line
the last line

结果:

$ ./a.out input.txt 
the first line
the second line
the last line
basic_ios::clear


推荐答案

你不能。标准说关于 getline


如果函数不提取任何字符, is.setstate(ios_base :: failbit)可能会引发 ios_base :: failure (27.5.5.4) p>

If the function extracts no characters, it calls is.setstate(ios_base::failbit) which may throw ios_base::failure (27.5.5.4).

如果文件以空行结束,即最后一个字符是'\\\
',则最后一次调用getline不会读取任何字符失败。实际上,如果不设置failbit,你想要如何终止循环? while 的条件永远是真的,它会永远运行。

If your file ends with an empty line, i.e. last character is '\n', then the last call to getline reads no characters and fails. Indeed, how did you want the loop to terminate if it would not set failbit? The condition of the while would always be true and it would run forever.

我认为你误解了failbit手段。它意味着该文件无法读取。它被用作上一个操作成功的标志。为了指示低级故障,使用badbit,但它对标准文件流几乎没有用处。 failbit和eofbit通常不应被解释为异常情况。 badbit另一方面应该,我会认为fstream :: open应该设置badbit而不是failbit。

I think that you misunderstand what failbit means. It does not mean that the file cannot be read. It is rather used as a flag that the last operation succeeded. To indicate a low-level failure the badbit is used, but it has little use for standard file streams. failbit and eofbit usually should not be interpreted as exceptional situations. badbit on the other hand should, and I would argue that fstream::open should have set badbit instead of failbit.

无论如何,上面的代码应该写为: / p>

Anyway, the above code should be written as:

try {
    ifstream inf(argv[1]);
    if(!inf) throw SomeError("Cannot open file", argv[1]);
    string line;
    while(getline(inf,line))
        cout << line << endl;
    inf.close();
} catch(const std::exception& e) {
    cout << e.what() << endl;
}

这篇关于使用getline(),而不设置failbit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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