How can I verify that std::istream::getline()
reached the delimiter, instead of just max-ing out the input buffer?
I realize that I can use gcount()
to determine whether fewer bytes than the buffer holds were read, but what if the line to read is exactly as long as the buffer? Reaching \n
would look exactly the same as not reaching \n
.
The conditions for terminating std::istream::getline()
are quite precise: If the function stops because n - 1
were stored but no newline was reached, the flag std::ios_base::failbit
is set. That is, you can just check the state of the stream to determine if a newline was reached.
That said, unless you need to protect against hostile sources of your data (e.g. an Internet connection send you data until you run out of memory, all on just one line), you should use the std::string
version:
std::string line;
std::getline(in, line);
Don't use member getline
at all. The following will always work, using the free function:
#include <string>
std::string line;
if (!std::getline(infile, line)) { /* error */ }
// entire line in "line"
(The answer to your actual question is that you must use member-getline
in a loop. But why bother.)