How Can I avoid char input for an int variable?

后端 未结 3 1637
栀梦
栀梦 2020-12-11 04:24

The program below shows a \'int\' value being entered and being output at the same time. However, when I entered a character, it goes into an infinite loop displaying the pr

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 05:16

    #include 
    #include  // for INT_MAX limits
    using namespace std;
    int main()
    {
        int num;
        cout << "Enter a number.\n";
        cin >> num;
        // input validation
        while (cin.fail())
        {
            cin.clear(); // clear input buffer to restore cin to a usable state
            cin.ignore(INT_MAX, '\n'); // ignore last input
            cout << "You can only enter numbers.\n";
            cout << "Enter a number.\n";
            cin >> num;
        }
    }
    

提交回复
热议问题