I have an overloaded operator in a class Fractionin C ++ that is designed to input input from standard input as an integer over an integer, i.e. 1/2or 32/4, and initializes the object based Fractionon these values. It works, but I'm having trouble finding errors.
std::istream& operator >>(std::istream& inputStream, Fraction& frac)
{
int inputNumerator, inputDenominator;
char slash;
if ((std::cin >> inputNumerator >> slash >> inputDenominator) && slash == '/')
{
if (inputDenominator == 0)
{
std::cout << "Denominator must not be 0." << std::endl;
throw std::invalid_argument("Denominator must not be 0.");
}
frac.numerator = inputNumerator;
frac.denominator = inputDenominator;
frac.reduce();
}
else
{
throw std::invalid_argument("Invalid syntax.");
}
return inputStream;
}
I call the method as follows:
Fraction frac(1, 2);
while (true)
{
try {
std::cout << "Enter a fraction in the form int/int: ";
std::cin >> frac;
std::cout << frac;
} catch (std::invalid_argument iaex) {
std::cout << "Caught an error!" << std::endl;
}
}
But whenever an error occurs, (I will enter something like garbage), this causes the loop to continue working without prompting for input. What is the reason for this?
source
share