gpt4 book ai didi

c++ - iostream sentry 在到达末尾时不设置 failbit

转载 作者:太空狗 更新时间:2023-10-29 22:56:56 25 4
gpt4 key购买 nike

对于以下代码:

#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

If is.rdbuf()->sbumpc() or is.rdbuf()->sgetc() returns traits​::​eof(), the function calls setstate(failbit | eofbit) (which may throw ios_­base​::​failure).

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

最佳答案

来自 std::istream::tellg 的引用:

if member fail returns true, the function returns -1.

来自 std::ios::fail 的引用:

Check whether either failbit or badbit is set

Returns true if either (or both) the failbit or the badbit error state flags is set for the stream.

At least one of these flags is set when an error occurs during an input operation.

检查此代码:

#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 在到达末尾时不设置 failbit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46448284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com