【问题标题】:Why does stream insertion of an empty streambuf fail?为什么空流缓冲区的流插入失败?
【发布时间】:2015-11-06 20:32:17
【问题描述】:

我使用的是simple file-slurp,我决定添加一些错误检查。我很惊讶一个空文件会出错。每个空序列也不会发生这种情况,“”工作正常。我还验证了 rdbuf() 正在返回一个非空指针。

#include <iostream>
#include <sstream>
using namespace std;

int main(int, char**){
    istringstream in(""); // Succeeds if non-empty
    stringstream sstr;
    if (sstr << in.rdbuf()) { // Succeeds if I replace in.rdbuf() with ""
        cout << "Read Successful\n";
    }else{
        cout << "Read Failed\n";
    }
}

【问题讨论】:

    标签: c++ iostream


    【解决方案1】:

    它设置了故障位,因为标准需要它。 (我现在觉得自己很愚蠢。我想我可能做错了什么。)2014 年 11 月草案的第 27.7.3.6.3.9 节说:

    如果函数没有插入字符,它会调用 setstate(failbit)(可能会抛出 ios_base::failure (27.5.5.4))。

    为什么委员会决定使这种行为不同于其他不认为插入任何内容为失败的序列插入(如 char* 和字符串)仍然是一个谜。但我现在知道这不是表明滥用对象的失败。

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 1970-01-01
      • 2018-06-28
      • 2016-05-27
      • 2012-01-19
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      相关资源
      最近更新 更多