使用(!cin>> x)来检测错误的用户输入

时间:2013-07-12 18:25:56

标签: c++ input io cin

这就是我正在使用的,我的代码应该读取用户输入,确保用户输入值1,2或0.任何其他值,它会发出一条提示用户输入的错误消息再试一次。现在它做了所有这些,但我有一个优化它的问题:

  • 当我输入任何正确的数字时,它不会在第一次注册时,我必须再次输入该值才能让程序正常工作。

    int LogicCalculator::m_userChoice(int &number)
    {
    number = num;//assignment
    //output
    std::cout<<"Selection: ";
    //input
    std::cin>>number;
    //Error Checking
    while((number < 0 || number > 3) || !(cin >> number))
    {
    cin.sync(); //discard unread characters in input buffer
    cin.clear(); //clear bad input flag
    
    cout<<"Only 1, 2 or 0 are acceptable entries. Exception No."<<endl;
    cout<<"Press Enter to Try Again"<<endl;
    
    if(cin.ignore())
    {
        system("cls");//clears the screen after the user presses Enter
    }
    
    m_Menu();
    m_userChoice(number);
    }
    return number;
    };
    

如果有人知道如何解决这个问题,我将非常感激不尽。

0 个答案:

没有答案
相关问题