Code to get user input not executing/skipping in C++

前端 未结 2 1587
刺人心
刺人心 2021-01-26 04:21

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

2条回答
  •  遥遥无期
    2021-01-26 04:33

    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;
    } 
    

提交回复
热议问题