rouge \n

Hi,
Can someone explain closer why a "\n" prints after the second "You wrote".
Terminal:
hi; a
You wrote: hi and a
bye; b
You wrote:
bye and b

Code:
string a,b;
for(int i{}; i < 2; i++)
{
getline(cin, a, ';');
cin >> b;
cout << "You wrote: " << a << " and " << b << endl;
}
The cin >> b; skips whitespace and then reads a word. That leaves newline into the stream.
Therefore, the next loop encounters
\nbye; b\n

in the stream. The getline gets
\nbye

discards the ';', and the >> handles the
 b

getline() and >> don't play well together.

getline() extracts data up to the terminating delimiter (\n unless specified) and then extracts and discards the delimeter.

>> ignores any preceding white space chars and then extracts up to the first white-space char which is NOT extracted.

Hence if you have a getline() following a >> then the white-space char terminating the >> is considered as input for the getline(). If this is the getline() terminating char then getline() will return with empty input.

One way around this is use cin.ignore() after the final >> before a getline().
Presumably OP means a "rogue" newline as opposed to a red one. :-)
Topic archived. No new replies allowed.