View Single Post
  #2 (permalink)  
Old December 17th, 2003, 05:47 AM
7stud 7stud is offline
Authorized User
 
Join Date: Jul 2003
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Quote:
quote:I first thought that a newline character was stuck somewhere in the input buffer.
That's exactly right. This is a problem that everyone encounters at some point along the C++ learning curve. The problem occurs when you use getline() after you use cin>> to read input. When you answer yes to continue, you type this:

y\n

The '\n' is entered into the input stream when you hit return. cin>> is defined to skip all leading "whitespace characters" and stop reading input when it encounters a whitespace character. Whitespace characters are spaces, as well as carriage returns and tabs. cin>> actually stops before reading in a trailing whitespace character.

[edit]
The getline() function, unlike cin>>, does not skip leading whitespace characters, but similar to cin>> it stops when it encounters a whitespace character, but unlike with cin>> when it encounters a whitespace character, like a '\n', the '\n' is read in before getline() stops.
[/edit]

So, after reading the input:

y\n

cin>> stops at the '\n', and the '\n' is next up to be read, and your subsequent use of getline() doesn't cause the program to pause for input because there is still a '\n' to be read in, and the getline() function is happy to do that. That makes it seem like those lines weren't executed.

To solve the problem, all you have to do is use cin.ignore() after using cin>> and before using getline().

cin.ignore(); //will skip one character of the input.

Other forms of cin.ignore():

cin.ignore(10); // will skip ten characters(1 is the default if you don't specify a size)

cin.ignore(50, '\n'); // will skip 50 characters or until it encounters a '\n', whichever occurs first.
Reply With Quote