当 getline 直到新行才读取时会发生什么?

What happens when getline does not read until new line?

看了很多相关的帖子,但是没有得到以下问题的答案。

考虑:

char buffer[4];
cin.getline(buffer, 4);
cout << buffer << endl;
cin.getline(buffer, 4);
cout << buffer << endl;

如果我在输入中输入 abc,我将有机会输入第二行,并且两行都正确显示在输出中。但是,如果我输入 abcd 或者,就此而言,任何超过三个字符的字符,我都不会输入第二行并且第二行输出为空。究竟是怎么回事?

我们看到 std::basic_istream<CharT,Traits>::getline()

extracts characters [...] until any of the following occurs (tested in the order shown):

  • end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)

  • the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.

  • count-1 characters have been extracted (in which case setstate(failbit) is executed).

If the function extracts no characters (e.g. if count < 1), setstate(failbit) is executed.

In any case, if count>0, it then stores a null character CharT() into the next successive location of the array and updates gcount().

在我们的例子中,因为我们为存储输入了太多字符,我们遇到了第三个条件,并且在流上设置了失败位。

可以使用 std::cin.clear() 取消设置失败位。