In the below code, I\'m running into an error when I try to get the user to input their name. My program just skips it over and goes right over to making the function calls with
After doing cin >> choice;
inside char showMenu()
, if a user inputs 1[ENTER]
, the char
consumes 1 character from cin, and the newline stays inside the stream. Then, when the program gets to getline(cin, name);
, it notices that there's still something inside cin
, and reads it. It's a newline character, so getline
gets it and returns. That's why the program is behaving the way it is.
In order to fix it - add cin.ignore();
inside char showMenu()
, right after you read the input. cin.ignore()
ignores the next character - in our case, the newline char.
And a word of advice - try not to mix getline
with operator >>
. They work in a slightly different way, and can get you into trouble! Or, at least remember to always ignore()
after you get anything from std::cin
. It may save you a lot of work.
This fixes the code:
char showMenu()
{
char choice;
cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
cin.ignore();
return choice;
}