简体   繁体   English

iostream sentry在到达终点时没有设置failbit

[英]iostream sentry doesn't set failbit when it has reached the end

for the following code: 对于以下代码:

#include <iostream>
#include <sstream>

using namespace std;

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

I'd expect the result be -1,1 not 1, 0. 我希望结果是-1,1而不是1,0。

tellg will first construct a sentry and then check fail() . tellg将首先构造一个sentry ,然后检查fail()

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

If is.rdbuf()->sbumpc() or is.rdbuf()->sgetc() returns traits​::​eof(), the function calls setstate(failbit | eofbit) (which may throw ios_base​::​failure). 如果is.rdbuf() - > sbumpc()或is.rdbuf() - > sgetc()返回traits :: eof(),则函数调用setstate(failbit | eofbit)(可能会抛出ios_base ::失败)。

so fail() should be true, and tellg should return -1. 所以fail()应该是true,而tellg应该返回-1。

From the ref of std::istream::tellg : std::istream::tellg的ref:

if member fail returns true, the function returns -1. 如果成员fail返回true,则函数返回-1。

From the ref of std::ios::fail : std::ios::fail的ref:

Check whether either failbit or badbit is set 检查是否设置了failbitbadbit

Returns true if either (or both) the failbit or the badbit error state flags is set for the stream. 如果为流设置了failbit或badbit错误状态标志中的任何一个(或两者),则返回true。

At least one of these flags is set when an error occurs during an input operation. 当在输入操作期间发生错误时,设置这些标志中的至少一个。

Check with this code: 检查此代码:

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

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

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