【问题标题】:In what practical case bool(std::ifstream) != std::ifstream::good()?在什么实际情况下 bool(std::ifstream) != std::ifstream::good()?
【发布时间】:2013-05-09 10:53:20
【问题描述】:

我想知道在什么情况下我们可以拥有:

bool(std::ifstream) != std::ifstream::good()

不同之处在于bool(std::ifstream) 不测试eof 位,而std::ifstream::good() 测试它。但实际上,如果尝试在文件结束后读取某些内容,则会引发 eof 位。但是,一旦您尝试这样做,我认为failbad 位也已设置。

因此,在什么情况下您只能提高 eof 位?

【问题讨论】:

  • 您可以独立于其他错误标志手动设置 eof 位,但我不确定在什么情况下您会这样做。 std::ifstream::setstate(std::ios::eofbit).

标签: c++ io stream eof


【解决方案1】:

简单地说,每当您遇到文件结尾而不尝试在其后面读取时。考虑一个文件“one.txt”,它只包含一个“1”字符。

无格式输入示例:

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    char chars[255] = {0};
    ifstream f("one.txt");
    f.getline(chars, 250, 'x');
    cout << f.good() << " != " << bool(f) << endl;
    return 0;
}

0 != 1
按任意键继续 。 . .

格式化输入示例:

#include <iostream>
#include <fstream>

int main()
{
    using namespace std;
    ifstream f("one.txt");
    int i; f >> i;
    cout << f.good() << " != " << bool(f) << endl;
    return 0;
}

0 != 1
按任意键继续 。 . .

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2010-09-26
    • 2010-11-08
    • 1970-01-01
    相关资源
    最近更新 更多