简体   繁体   中英

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;
    }


}

The output is

OUTPUT: 1234

when I feel like all sources tell me input should test as false and there should be no ouput. From the standard (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)).

Since 4 values get stored, failbit should be getting set. Some other sources give a bit differing but still confusing input on this function. 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).

Again, the deliminting character '\\n' is not found after the 4 , and so failbit should be getting set. Cppreference says a similar thing. What am I missing here?

Yes it reads n-1 characters and it never encountered '\\n' but you missed the first point

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

Since you read in exactly what was in the stream the eofbit gets set and you get the input.

If we add

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

You can see that is indeed what happened( live example )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM