Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

2.00

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading