对于以下代码:

#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



因此fail()应该为true,并且tellg应该返回-1。

最佳答案

std::istream::tellg 的引用:



std::ios::fail 的引用:



检查以下代码:

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

关于c++ - iostream sentry到达终点时未设置故障位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46448284/

10-09 20:57