Possible Duplicate:
std::string to float or double
I am writing a calculator (learning C++), and just decided to make a calculator, since that was the first thing I did when learning Java.
The program does the following:
when grabbing a number from the user in Java I used Double.parseDouble(number) to check if what they entered is a number or not.
Is there a similar command in C++? Ive been doing research and it seems like you have to use tricks such as comparing it to ASCII equivalents etc.. basically a ton of code for a simple task... so before i take that route, I wanted to stop by here and see if perhaps there is some sort of call I can make to check if the input is a number. I need it to validate negatives, zero and positives, as well as numbers with decimals... everything else should be rejected and the user should be asked for input again.
When I did it in Java I used try/catch statement and if the input was invalid it would return the method (in other words, itself) so it would loop and ask the user for input again.
Thanks!
You can use strtod
. It handles underflow and out of range values in a convenient way.
Additionally, as Joachim Pileborg notes, if you use C++11 compliant compiler, there is std::stod
in the standard library.