0

I have seen quite a number of related posts, but did not get an answer to the following question.

Consider:

char buffer[4];
cin.getline(buffer, 4);
cout << buffer << endl;
cin.getline(buffer, 4);
cout << buffer << endl;

If I enter abc on input, I am given a chance to enter the second line and both lines appear correctly in the output. However, if I enter abcdor, for that matter, anything longer than three characters, I do not get to enter the second line and the second line of output is empty. What exactly is going on?

AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68
  • I assume it has to do with the `\n` – Tony Tannous Jan 15 '20 at 10:22
  • Possible duplicate (maybe there are better dupes out there, not voting): [Reading two line continuously using getline function in c++](https://stackoverflow.com/questions/57087499/reading-two-line-continuously-using-getline-function-in-c) – Yksisarvinen Jan 15 '20 at 10:26
  • @TonyTannous That's what the title of the question says. I am trying to understand what exactly is happening. – AlwaysLearning Jan 15 '20 at 10:26

1 Answers1

3

We see that std::basic_istream<CharT,Traits>::getline()

extracts characters [...] until any of the following occurs (tested in the order shown):

  • end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)

  • the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.

  • count-1 characters have been extracted (in which case setstate(failbit) is executed).

If the function extracts no characters (e.g. if count < 1), setstate(failbit) is executed.

In any case, if count>0, it then stores a null character CharT() into the next successive location of the array and updates gcount().

In our case, because we've entered too many characters for the storage, we hit the third condition, and the fail bit is set on the stream.

The fail bit can be unset using std::cin.clear().

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • 1
    Putting `cin.clear()` resolved the problem, so that the second `getline` continues to read the line that was not completely read by the first one. – AlwaysLearning Jan 15 '20 at 10:41