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

前端 未结 2 1586
刺人心
刺人心 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;
    } 
    
    0 讨论(0)
  • 2021-01-26 04:33

    from looking at code showMenu function has problem. and it's not returning asccii equivalent of '1' that is: 31 integer. try printing value returned by showmenu. you will get that

    UPDATE: It is because cin in delimited by ' '(whitespace) and getline by '\n' character, so when enter name and press enter cin in showmenu will consume whole string except '\n' from istream and that is read by getline. to see this when it ask for choice enter string like 1 myname (1 whitespace myname)and press ENTER will display name. now cin will read 1 in choice and myname in name by getline.

    0 讨论(0)
提交回复
热议问题