Possible Duplicate:
how do I validate user input as a double in C++?
I am new to C++, and I have a function in which I am wanting the user to input a double value. How would I go about insuring that the value input was of the correct datatype? Also, how would an error be handled? At the moment this is all I have:
if(cin >> radius){}else{}
I using `try{}catch(){}, but I don’t think that would the right solution for this issue. Any help would be appreciated.
If
ostream& operator>>(ostream& , T&)fails the extraction of formatted data (such as integer, double, float, …),stream.fail()will be true and thus!streamwill evaluate to true too.So you can use
or simply
It is important to
ignorethe rest of the line, sinceoperator>>won’t extract any data from the stream anymore as it is in a wrong format. So if you removeyour loop will never end, as the input isn’t cleared from the standard input.
See also:
std::basic_istream::ignore(cin.ignore)std::basic_istream::fail(cin.fail())std::numeric_limits(used for the maximum number of ignored characters, defined in<limits>).