简体   繁体   English

使用getline()而不设置failbit

[英]Use getline() without setting failbit

Is it possible use getline() to read a valid file without setting failbit ? 是否可以使用getline()来读取有效文件而不设置failbit I would like to use failbit so that an exception is generated if the input file is not readable. 我想使用failbit以便在输入文件不可读时生成异常。

The following code always outputs basic_ios::clear as the last line - even if a valid input is specified. 以下代码始终输出basic_ios::clear作为最后一行 - 即使指定了有效输入。

test.cc: test.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

results: 结果:

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

You can't. 你不能。 The standard says about getline : 关于getline的标准说:

If the function extracts no characters, it calls is.setstate(ios_base::failbit) which may throw ios_base::failure (27.5.5.4). 如果函数没有提取任何字符,则调用is.setstate(ios_base::failbit) ,这可能会抛出ios_base::failure (27.5.5.4)。

If your file ends with an empty line, ie last character is '\\n', then the last call to getline reads no characters and fails. 如果你的文件以空行结束,即最后一个字符是'\\ n',则最后一次调用getline不会读取任何字符并失败。 Indeed, how did you want the loop to terminate if it would not set failbit? 实际上,如果不设置failbit,你是如何想要循环终止的呢? The condition of the while would always be true and it would run forever. 的的条件while将永远是真实的,它会永远运行下去。

I think that you misunderstand what failbit means. 我认为你误解了failbit的含义。 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. 为了表示低级故障,使用了badbit,但它几乎没有用于标准文件流。 failbit and eofbit usually should not be interpreted as exceptional situations. failbit和eofbit通常不应被解释为例外情况。 badbit on the other hand should, and I would argue that fstream::open should have set badbit instead of failbit. 另一方面,badbit应该,并且我认为fstream :: open应该设置badbit而不是failbit。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM