Calculating a "char*" calculation and give back the result as a "double" (or "float")

i want to calculate the "char*" and give back the result as a "double" (or "float").

char* calculation = "2+2*2";
double result = atof(calculation);

double result:


The problem is that it just doesn’t calculate automatically and just stops scanning the "char*" at the "+".
Any ideas?

And NO I don’t want to declare "calculation" as a "double".

>Solution :

atof doesn’t do what you think it does. It converts the string to double until it reaches a character in the string that is invalid, at which it stops. In your string that would be the "+" sign. So the result is 2.0, which is the double representation of "2".

You will have to write your own expression evaluation routine, or find a pre-existing one. Neither C nor C++ provide one in their standard libraries.

Leave a Reply