I’m trying to read multiple Strings and ints from the user. I want to take pairs of Name and Age and keep doing it until the user types in “done”. But my do-while crashes early on, and i can’t figure out why?
int number;
string name;
do
{
cout << "Your name: " ;
getline(cin, name);
cout <<name<< " age: " ;
cin >> number;
}
while (name!="done");
Edit: Also after entering “done”, i have to enter “done” also on age, why is that?
I tried to run your program in VS 2010, and even when I entered a valid number, the program would, to my surprise skip reading the next name.
It seems to me that
cin >> numberdoesn’t swallow the ‘\n’ I naturally entered after the number.I attempted adding a call to getchar() after each
cin >> numberand the program suprisingly started working as expected.So the conclusion is, that you should clean()/ignore() after
cin >> numbereven after the number entered was OK, or resort to using getline() (and then parsing) for reading numbers.If you want not to input “done”‘s age then you have to break out of the loop immediately after it’s entered. My final code: