无效的int输入陷入无限循环

无效的int输入陷入无限循环

本文介绍了无效的int输入陷入无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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值,它进入一个无限循环,不知道为什么。任何想法?

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?

推荐答案

if (cin.fail() ... )

一旦输入无效的值(例如 char ),流中的failbit将打开, validNum 将始终返回false,导致无限循环。

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

这篇关于无效的int输入陷入无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:33