对于 std::cin,是否存在仅设置 EOFBIT 而未设置 FAILBIT 的情况?

For std::cin, is there a situation where only EOFBIT is set but not FAILBIT?

提问人:Anthony 提问时间:9/28/2018 更新时间:9/28/2018 访问量:218

问:

我是一个完全的初学者,我试图了解 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 = 100ios_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)。

我错过了什么?

C++ CIN EOF iStream

评论

0赞 9/28/2018
latedev.wordpress.com/2012/12/04/all-about-eof 可能会有所帮助
0赞 Igor Tandetnik 9/28/2018
回答标题中的问题时,未格式化的函数(如 )在到达文件末尾时设置,并且仅在它们甚至无法读取一个字符时设置。虽然你的帖子的正文似乎与标题没有任何关系 - 它主要是关于Ctrl + Z对控制台输入的作用。cin.get(buffer, size)eofbitfailbit
0赞 Anthony 9/28/2018
@IgorTandetnik 这是有道理的。但是 cin 如何识别文件的末尾呢?因此,在示例输入 1 和 2 中,它显然没有将 CTRL-Z 视为 eof,因为 eofbit 没有被触发。但对于 3 和 4,它确实如此。
0赞 Anthony 9/28/2018
@IgorTandetnik 澄清一下,帖子的标题和正文在以下意义上相关: 我似乎无法从控制台中提出一个测试用例,该用例可以在不设置 failbit 的情况下设置 eofbit。
0赞 MSalters 9/28/2018
Windows 不是 Linux; 不是由操作系统级组件提供的。“Windows 版本 6.3.9600”不相关,编译器版本是。istream

答: 暂无答案