gpt4 book ai didi

c++ - istream::getline failbit 没有设置?

转载 作者:行者123 更新时间:2023-11-28 05:55:03 27 4
gpt4 key购买 nike

#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 )

关于c++ - istream::getline failbit 没有设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34343455/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com