我是一个完整的初学者,他试图围绕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
当输入缓冲区([CTRL-Z]字符除外)为空时,将设置eofbit和failbit。
示例输入4:[CTRL-Z] 123456789
输出:
Read failed. Current state of cin: 110
与第三种情况相同的输出,[CTRL-Z]之后的内容被忽略。
似乎cin不可能成功地将[CTRL-Z]读取为EOF字符(也就是说,已设置eofbit,但未设置failbit)。在cin确实将[CTRL-Z]读取为字符的情况下,它不会将其视为EOF字符(示例1和2中未设置eofbit)。
我想念什么?