質問

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:

  1. Asks the user for the first number
  2. Asks what the user wants to do with the number (-,+,*,/)
  3. Asks for the second number
  4. Displays the result.

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.

他のヒント

Use the function double atof(const char*) ;

example usage:

const char* = "3.14159";
double pi = atof(myDouble);

How about using isdigit function.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top