istream::getline failbit 没有设置?

istream::getline failbit not getting set?

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

int main(){

    istringstream input("1234");

    char c[5];

    while(input.getline(c, 5, '\n')){
        cout << "OUTPUT: " << c << endl;
    }


}

输出为

OUTPUT: 1234

当我觉得所有消息来源都告诉我 input 应该测试为 false 并且应该没有输出时。来自标准 (N3337) [27.7.2.3]/18:

Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts characters and stores them into successive locations of an array whose first element is designated by s. Characters are extracted and stored until one of the following occurs:

  1. end-of-file occurs on the input sequence (in which case the function calls setstate(eofbit));
  2. traits::eq(c, delim) for the next available input character c (in which case the input character is extracted but not stored);320
  3. n is less than one or n - 1 characters are stored (in which case the function calls setstate( failbit)).

由于存储了 4 个值,因此应该设置 failbit。其他一些来源对此函数的输入略有不同,但仍然令人困惑。 Cplusplus:

The failbit flag is set if the function extracts no characters, or if the delimiting character is not found once (n-1) characters have already been written to s. Note that if the character that follows those (n-1) characters in the input sequence is precisely the delimiting character, it is also extracted and the failbit flag is not set (the extracted sequence was exactly n characters long).

同样,在 4 之后找不到分隔符 '\n',因此应该设置 failbitCppreference 说了类似的话。我在这里错过了什么?

是的,它读取了 n-1 个字符,但从未遇到 '\n' 但您错过了第一点

end-of-file occurs on the input sequence (in which case the function calls setstate(eofbit));

由于您准确读取了流中的内容,eofbit 得到设置并且您得到了输入。

如果我们加上

std::cout << input.eof();

你可以看到确实是这样(live example)