DarkPotatoKing
DarkPotatoKing

Reputation: 499

How to throw an std::iostream failure in C++?

How do I manually throw an std::iostream::failure? I have a try-catch loop that catches an exception when the user tries to input a non-integer string, however it does not throw an exception if the user tries to input a float since it will try to read everything before the decimal point in a float value. My solution is to manually throw the exception if there is still data remaining in the stream, how do I do that?

/*
Sample Implementation Code in C++
Handling Inputs from User in C++
This code only stops running when the user
inputs the appropriate values. Otherwise, the program
will continue asking the user for input.
*/

#include <iostream>
#include <limits> //numeric_limits
#include <stdexcept>

int main() {
    std::cin.exceptions(std::ios::failbit); // set exceptions to be thrown when a failbit is set
    int num = 0;
    int den = 0;

    while (true) {
        try {
            std::cout << "Enter numerator: ";
            std::cin >> num;
            if(std::cin.peek() != '\n') {
                //HOW TO DO THIS PART?
                std::iostream::failure e;
                throw e;
            }
            std::cout << "Enter denominator: ";
            std::cin >> den;
            std::cout << "The quotient is " << num/den << std::endl;
        } catch (std::iostream::failure& e){
            std::cout << "Input should be an integer." << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    return 0;
}

Upvotes: 0

Views: 2915

Answers (1)

DarkPotatoKing
DarkPotatoKing

Reputation: 499

Apparently it's as simple as:

throw std::iostream::failure("");

the important thing I forgot is the empty string ("") since it has a constructor that takes a string argument but not a void argument.

Upvotes: 1

Related Questions