How should I make my program correctly handle all user inputs?

92 views Asked by At

I want to create an input system that can correctly handle all inputs. The desired user input is an double. When the user inputs a string, the stringstream fails and the exception is handled. However, the program can't handle inputs such as "3245 2345 5" and "21523i4jf", instead of labeling them as improper inputs it registers the number at the beginning of the string and passes that to double number without raising an exception.

while (true)
{
    string user_input;
    cout << "Your Choice: ";
    getline (cin, user_input);
    cout << endl;

    if (user_input == "quit")
    {
        break;
    }

    try
    {
        double number;
        stringstream stringstream_input;

        stringstream_input << user_input;
        stringstream_input >> number;

        if (stringstream_input.fail())
        {
            throw 90;
        }

        cout << number << endl << endl;
    }

    catch (int x)
    {
        cout << "Please enter a valid input!" << endl << endl;
    }
}
1

There are 1 answers

0
user0042 On

You can use std::stod() to handle that correctly.

try {
    number = std::stod(user_input);
}
catch(const std::invalid_argument& e) {
    std::cerr << "Invalid input '" << user_input << "'" << std::endl;
}