Problem with ifstream::getline()

Dear Rooters

Even though this is more a C++ question any help would be appreciated.

I have the following code fragment to read a certain line of a text file:

   char nextline[16635];
   ifstream input(infile, ios::in);

   while (strcmp(sample, nextline) != 0) {
      input.getline(nextline, 16635, '\n');
      if (input.eof())  return -1;
   }

When testing the code everything was fine, but when reading the final large text file,
my computer was stuck in an infinite loop (I have almost burnt my CPU).
The following change in my code solved to problem partly, i.e. my program returned:

   while (strcmp(sample, nextline) != 0) {
      input.getline(nextline, 16635, '\n');
      if (input.eof() || input.fail())  return -1;
   }

The reason was that the text file had one line which had a size of 150,000 characters!

Looking up the behavior of ifstream::getline(buf, limit, delim) in different C++ text
books gives me different answers, e.g.:
Schildt: getline() extracts characters until either limit-1 characters are read, or
or until delim is found or until the end of the file is reached.
Lippman: The invocation of getline will extract at most limit-1 characters… If
either the end-of-file is reached or the delim character is encountered, getline()
will extract less than limit-1 characters.

This makes me wonder what the correct behavior should be.
Why did the first code fragment result in an infinite loop trying to read lines
forever w/o reaching eof?
Is there a way to read only the first limit characters of a line and then read
the next line w/o looking for delim, when the line is longer than limit?

Best regards
Christian

According to gcc.gnu.org/ml/gcc-prs/2002-04/msg00546.html the first behavior is acceptable and is to due to improper checking the ‘result’ of the getline operation.
In practice, it was either reading over and over the same line or just reading nothing else.
Your solution is acceptable. Possibly a better solution might be:[code]char nextline[16635];
ifstream input(infile, ios::in);

while (strcmp(sample, nextline) != 0) {
input.getline(nextline, 16635, ‘\n’);
if (! input.good()) return -1;
}[/code]

Cheers,
Philippe.

Dear Philippe

Thank you. This means that the behavior of getline() is not satisfactorily,
probably I need to loop through get() if I want to be more flexible.

Best regards
Christian