The problem that you are having is because you are mixxing formatted (>>) and unformatted (getline, ignore) input operations.
Consider the input like an array of characters:
With the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main()
{
string name;
cout << "What is your name? " << flush;
cin >> name;
cout << "Hello " << name << "!\n";
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
return 0;
}
|
the input fails.
Line 10 reads up to the first whitespace character, but does
not discard it:
The ENTER key ('\n') that the user pressed after typing "Jimmy" is still there. Line 12 reads it and then the program quits.
If you change line 10 to read properly:
then the entire line,
including the newline (ENTER key), gets read:
Now the program gets to line 12 and finds that there isn't any input to be read -- so it waits for the user to enter some. Press the ENTER key:
Now line 12 can read that last ENTER key ('\n'):
and terminate.
The other way to change line 10 is to add an
ignore() after the read:
1 2
|
cin >> name;
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
|
The difference is that
getline() reads the
entire line, but
operator>> only reads up to the first whitespace character. To see the difference, try the program with the first correction and enter "Jimmy Jackson" when it asks a name. Then try the program with the second correction and again enter "Jimmy Jackson" as the name.
Hope this helps.
[edit] Fixed a typo.