提问人:Anthony 提问时间:9/28/2018 更新时间:9/28/2018 访问量:218
对于 std::cin,是否存在仅设置 EOFBIT 而未设置 FAILBIT 的情况?
For std::cin, is there a situation where only EOFBIT is set but not FAILBIT?
问:
我是一个完全的初学者,我试图了解 std::istream 的工作原理。
运行了一些测试用例(在 Windows 机器上 - Windows 版本 6.3.9600),我写了这个简单的程序:
int main()
{
char ch{0};
while (true)
{
if (cin >> ch)
{
cout << ch << " is read. ASCII Code: " << int(ch)
<< " current state of cin : " << bitset<3> (cin.rdstate())
<< endl;
}
else
{
//cin.fail()
cout << "Read failed. Current state of cin: "
<< bitset<3> (cin.rdstate()) << endl;
cin.clear();
}
}
}
我应该注意在我的机器上,并且ios_base::failbit = 100
ios_base::eofbit = 010
输入示例 1:12345[CTRL-Z]
其中输出:
1 is read. ASCII Code: 49 Current state of cin: 000
2 is read. ASCII Code: 50 Current state of cin: 000
3 is read. ASCII Code: 51 Current state of cin: 000
4 is read. ASCII Code: 52 Current state of cin: 000
5 is read. ASCII Code: 53 Current state of cin: 000
→ is read. ASCII Code: 26 Current state of cin: 000
此时,程序将等待进一步的输入。
输入示例2:12345[CTRL-Z]6789
其中输出:
1 is read. ASCII Code: 49 Current state of cin: 000
2 is read. ASCII Code: 50 Current state of cin: 000
3 is read. ASCII Code: 51 Current state of cin: 000
4 is read. ASCII Code: 52 Current state of cin: 000
5 is read. ASCII Code: 53 Current state of cin: 000
→ is read. ASCII Code: 26 Current state of cin: 000
...等待进一步的输入。 仍然没有设置任何标志,但 CTRL-Z 之后的字符被完全忽略,就好像它们已从流中删除一样。为什么这里没有触发EOFBIT?我还查找了替换字符(ASCII 代码 26),它应该是不可打印的,但它仍然使用右箭头符号打印(为什么?而且由于 eofbit 在读取时未触发,因此我假设 Windows 不会将 Substitute 字符视为 EOF 字符......
示例输入 3:[CTRL-Z]
输出:
Read failed. Current state of cin: 110
当输入缓冲区为空时,将设置 eofbit 和 failbit,但 [CTRL-Z] 字符除外。
示例输入 4:[CTRL-Z] 123456789
输出:
Read failed. Current state of cin: 110
与第三种情况的输出相同,并且 [CTRL-Z] 之后的内容被忽略。
似乎没有 cin 成功读取 [CTRL-Z] 作为 EOF 字符的情况(即,设置了 eofbit,但未设置 failbit)。如果 cin DOES 将 [CTRL-Z] 读取为字符,则不会将其视为 EOF 字符(示例 1 和 2 中未设置 eofbit)。
我错过了什么?
答: 暂无答案
评论
cin.get(buffer, size)
eofbit
failbit
istream