Search code examples
c++istream

std::getline: delimiting character vs. character count


The member function istream& istream::getline(char* s, streamsize n, char delim); enables you to extract characters from the stream until one of 3 things happens:

  1. the specified delimiting character is found,
  2. n - 1 characters are read from the stream, or
  3. An EOF or error occurs

Obviously, condition 3 (an error occurs) is easy to detect. But how can the caller distinguish between conditions (1) and (2)? How can you tell if a delimiting character was, or not? It's possible that n - 1 characters were read, but a delimiting character wasn't found.


Solution

  • According to http://en.cppreference.com/w/cpp/io/basic_istream/getline

    In situation 3, setstate(eofbit) will be executed.

    In situation 2, setstate(failbit) will be executed.