【问题标题】:invalid int input gets stuck in an infinite loop [duplicate]无效的int输入陷入无限循环[重复]
【发布时间】:2013-10-29 07:25:33
【问题描述】:
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;
}

我要做的是确保分母不为零,并且他们只输入数字。除以零代码可以正常工作,但是当您输入 char 值时,它会进入无限循环并且不知道为什么。有什么想法吗?

【问题讨论】:

    标签: c++ infinite-loop


    【解决方案1】:
    if (cin.fail() ... )
    

    一旦输入无效值(即char),流中的故障位将打开,validNum 将始终返回 false,从而导致无限循环。

    您需要在每次调用后清除错误状态并忽略其余输入:

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

    【讨论】:

    • 太棒了,完美运行。出于好奇 numeric_limits<:streamsize>::max() 是如何工作的以及它是做什么的
    • @JuanSierra numeric_limits::max 返回给定类型的最大值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2013-05-28
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多