I looked at some other questions and I\'m too newbish at C++ to know if they applied to my question here..
Basically when show the output of \"name\", if I type in
That's because the newline
from the "How much money do you have?" reply is still in the input buffer. In general it is not a good idea to mix item input and line-based input (whether using C and scanf
/fgets
or C++ >>
and getline
), because you get these sort of problems.
You can fix this particular situation by using char dummy = cin.get();
before somewhere before getline
, however, you have to do that every time you switch from "item input" to "line input", and if you later change the order, you have to remember to move the cin.get()
along.
A better solution is to ALWAYS use line-based input, and then use stringstream
to get the data out of the string, so something like this:
string ageString;
getline(cin, ageString);
stringstream ageSs(ageString);
if (!ageSs >> age)
{
cout << "Bad input" << endl;
exit(1); // You may of course want to repeat rather than exit...
}
That way, you are reading a whole line, no matter what the input is.