Channel72
Channel72

Reputation: 24739

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.

Upvotes: 1

Views: 368

Answers (3)

Pete Becker
Pete Becker

Reputation: 76458

You can unask the question. Use getline(std::basic_istream&, std::basic_string&, Elem delim);. Or if you're using C++11, that's getline(std::basic_istream&&, std::basic_string&, Elem delim);. That is, read into a std::string. If you do that, you don't have to deal with array sizes.

Upvotes: 1

Drew Dormann
Drew Dormann

Reputation: 63946

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.

Upvotes: 3

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361712

You can use std::istream::gcount() to know the count of characters read, and compare it with n to figure out the answers to your questions. Also, the output buffer can be searched to figure out the delim.

Upvotes: 0

Related Questions