【问题标题】:iostream sentry doesn't set failbit when it has reached the endiostream sentry 到达末尾时未设置故障位
【发布时间】:2018-03-08 23:10:56
【问题描述】:

以下代码:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    istringstream iss("a");
    iss.get();
    cout << iss.tellg() << endl;  // 1
    cout << iss.fail() << endl;   // 0
}

我希望结果是 -1,1 而不是 1, 0。

tellg 将首先构造一个sentry,然后检查fail()

根据http://eel.is/c++draft/istream::sentry#2

如果 is.rdbuf()->sbumpc() 或 is.rdbuf()->sgetc() 返回 traits​::​eof(),函数调用 setstate(failbit | eofbit)(其中 可能会抛出 ios_base​::​failure)。

所以fail() 应该为真,tellg 应该返回 -1。

【问题讨论】:

  • 在我要求流读取一个字符并且它读取一个字符之后,fail() 会返回 true,这对我来说似乎很奇怪。
  • 您也可以/应该检查get 的返回值。

标签: c++ stream iostream


【解决方案1】:

来自std::istream::tellg的参考:

如果成员fail返回true,则函数返回-1。

来自std::ios::fail的参考:

检查是否设置了failbitbadbit

如果为流设置了 failbit 或 badbit 错误状态标志中的一个(或两者),则返回 true。

当一个错误发生时,这些标志中至少有一个被设置。 输入操作。

检查此代码:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    istringstream iss("a");
    iss.get();
    cout << iss.fail() << endl;   // 0
    cout << iss.tellg() << endl;  // 1
    cout << iss.eof() << endl;    // 0
}

【讨论】:

  • 所以这就是哨兵没有正确设置故障位的原因 | eofbit。
  • 是的@FunkyBaby,如果你想接受我的回答顺便说一句! :)
猜你喜欢
  • 2012-06-16
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2021-05-02
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多