I have an overloaded operator in my Fraction
class in C++ which is designed to take input from standard input in the form of an integer over an integer i.e. 1/2
or 32/4
and initialize a Fraction
object based off of those values. It works, but I'm having trouble catching errors.
// gets input from standard input in the form of (hopefully) int/int
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 invoke the method like this:
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 is thrown, (I'll enter something like garbage
) this causes the loop to go on forever without asking for input. What is the reason for this?