且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中获取用户输入未执行/跳过的代码

更新时间:2023-02-12 19:54:09

char showMenu()中执行cin >> choice;之后,如果用户输入1[ENTER],则char会消耗cin中的1个字符,换行符停留.然后,当程序进入getline(cin, name);时,它会发现cin内还有东西,并进行读取.这是换行符,因此getline可以获取并返回.这就是程序表现方式的原因.

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.

为解决此问题,请在读取输入后立即在char showMenu()内添加cin.ignore();. cin.ignore()忽略下一个字符-在我们的例子中为换行符.

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.

还有个建议-尝试getlineoperator >>混合使用.它们的工作方式略有不同,可能会惹上您的麻烦!或者,至少要记住从std::cin中获取任何内容后,始终要按ignore().它可以为您节省很多工作.

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.

这可以修复代码:

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