invalid int input gets stuck in an infinite loop [duplicate]

ぐ巨炮叔叔 提交于 2019-12-19 11:23:03

问题


do
{
    cout << "Enter the numerator and denominator of the first fraction: ";
    cin >> a >> b;
    cout << endl;
    cout << "Enter the numerator and denominator of the second fraction: ";
    cin >> c >> d;
    cout << endl;
} while (!validNum(a, b, c, d));

...

bool validNum(int num1, int num2, int num3, int num4)
{
    if (cin.fail() || num2 == 0 || num4 == 0)
    {
        if (num2 == 0 || num4 == 0)
        {
            cout << "Invalid Denominator. Cannot divide by 0" << endl;
            cout << "try again: " << endl;
            return false;
        }
        else
        {
            cout << "Did not enter a proper number" << endl;
            cout << "try again: " << endl;
            return false;
        }
    }
    else
        return true;
}

What I am trying to do is make sure the denominator is not zero and that they only enter numbers. The dividing by zero code works fine but when you enter a char value it enters an infinite loop and do not know why. Any ideas?


回答1:


if (cin.fail() ... )

Once you enter an invalid value (i.e a char), the failbit in the stream will be on and validNum will invariably return false, causing an infinite loop.

You need to clear the error state and ignore the rest of the input after each call:

if (std::cin.fail())
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}


来源:https://stackoverflow.com/questions/19483750/invalid-int-input-gets-stuck-in-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!