【问题标题】:Check if all values were successfully read from std::istream检查是否从 std::istream 成功读取所有值
【发布时间】:2013-01-01 21:58:20
【问题描述】:

假设我有一个文件

100 text

如果我尝试使用 ifstream 读取 2 个数字,它将失败,因为 text 不是数字。使用 fscanf 我会通过检查它的返回码知道它失败了:

if (2 != fscanf(f, "%d %d", &a, &b))
    printf("failed");

但是当使用 iostream 而不是 stdio 时,我怎么知道它失败了?

【问题讨论】:

    标签: c++ iostream


    【解决方案1】:

    它实际上(如果不是更)简单:

    ifstream ifs(filename);
    int a, b;
    if (!(ifs >> a >> b))
       cerr << "failed";
    

    顺便说一下,习惯这种格式。因为它非常很方便(对于通过循环继续积极进展更是如此)。

    【讨论】:

    • -1 因为: 1. 我不喜欢带有副作用的 if 条件。 2. 这打破了“最小惊讶原则”——人们不知道从(ifs &gt;&gt; a &gt;&gt; b) 表达式的值中可以期待什么。
    【解决方案2】:

    如果有人使用带有-std=c++11-std=c++14 的GCC,她可能会遇到:

    error: cannot convert ‘std::istream {aka std::basic_istream<char>}’ to ‘bool’
    

    为什么? C++11 标准使 bool 运算符调用显式 (ref)。因此有必要使用:

    std::ifstream ifs(filename);
    int a, b;
    if (!std::static_cast<bool>(ifs >> a >> b))
      cerr << "failed";
    

    我个人更喜欢使用fail函数:

    std::ifstream ifs(filename);
    int a, b;
    ifs >> a >> b
    if (ifs.fail())
      cerr << "failed";
    

    【讨论】:

    • 失败时,你不应该做类似throw std::system_error(errno, std::generic_category()); 的事情吗?无论如何,+1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 2011-09-11
    • 2011-09-13
    相关资源
    最近更新 更多