How to throw std :: invalid_argument error?

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.

// 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 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?

+4
source share
1 answer

, , :

, cin inputNumerator >> slash >> inputDenominator, . else ( , catch ).

, cin , , . , cin . , , , ignore d:

if ((std::cin >> inputNumerator >> slash >> inputDenominator) && slash == '/')
{
  /* ... */
}
else
{
    std::cin.clear(); // reset the fail flags
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore the bad input until line end
    throw std::invalid_argument("Invalid syntax.");
}
+6

Source: https://habr.com/ru/post/1526303/


All Articles