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?
Once you enter an invalid value (i.e a
char
), the failbit in the stream will be on andvalidNum
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: