How to deal with non-number inputs?

How to deal with non-number inputs?

by Faisal Halabeya -
Number of replies: 1

I'm trying to make sure the user inputs a number for the initial velocity. So far I have:

    // v0 will hold the initial speed of the ball
    double v0 = -1;

    cout << "State the initial velocity in m/s:";
    cin >> v0;
 
    // do not proceed until v0 is larger than 0
    while (v0 <= 0.0) {
        cout << "Please enter a number larger than 0.\n";
        cin >> v0;
    }

Is this sufficient, or do I need to also check for non-number inputs? Also, if the user inputs a number like "3", will that cause problems since it looks like an int rather than a double?

In reply to Faisal Halabeya

Re: How to deal with non-number inputs?

by Ramses van Zon -
To be resilient against non-number inputs is a bit tricky, you'd need to first read in a string, then try to convert it to a double with std::stod while catching exceptions that std::stod may throw. It won't throw an exception if it looks like an int, in that case it will just store the integer value in the double.