All user input is followed by an ENTER key press.
Therefore, you must eat a newline everytime you get input.
However, using >> does
not eat them unless they are in the way.
For example, the program
1 2 3 4 5 6 7 8 9
|
#include <iostream>
using namespace std;
int main()
{
cout << "How old are you? " << flush;
double age;
cin >> age;
return 0;
}
|
D:\prog\foo> a.exe
What is your age?
24
D:\prog\foo> |
when compiled, will accept any number of ENTER key presses
before you type in a valid number. But it will
not read the ENTER key you pressed
after you typed in a valid number!
So, if you chage the program to read
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How old are you? " << flush;
double age;
cin >> age;
cout << "What is your name? " << flush;
string name;
getline( cin, name );
cout << "Hello " << name
<< ", you are " << (int)age
<< " years old!\n";
return 0;
}
|
D:\prog\foo> a.exe
What is your age? 24
What is your name?
Hello , you are 24 years old!
D:\prog\foo> |
you will notice that the program never gives you a chance to enter your name.
That's because you didn't get rid of the newline (ENTER key press) from when you entered an age.
Modify the program once more to get rid of that pesky ENTER key press from the age line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main()
{
cout << "How old are you? " << flush;
double age;
cin >> age;
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
cout << "What is your name? " << flush;
string name;
getline( cin, name );
cout << "Hello " << name
<< ", you are " << (int)age
<< " years old!\n";
return 0;
}
|
D:\prog\foo> a.exe
What is your age? 24
What is your name? Jennifer
Hello Jennifer, you are 24 years old!
D:\prog\foo> |
Now both of your inputs (lines 9-10 and line 13) read and ignore the ENTER key the user pressed after typing her age and name.
And that is the cause and solution to your problem. Make sure that every time you use >> you follow it by a line like line 10 (don't forget to #include <limits> at the top of your program too). Then things like
cin.
get() and
getline() will start behaving the way you expect -- because the input buffer is synchronized with your brain.
Hope this helps.