Hi
What is the simplest way to calculate string like:
String^ numbers = "15+3*2";
In php I used eval(), but I can't find a function like eval() in c++.
Thx!
Hi
What is the simplest way to calculate string like:
String^ numbers = "15+3*2";
In php I used eval(), but I can't find a function like eval() in c++.
Thx!
Simplest way is manually. Either that or find some library or copy/paste existing code. Theres no standard function to do something like that.
You have to manually parse the string, converting the numbers to actual numbers (ints, floats, whatever your using). You also have to manually look for the char operators (+, -, etc) and do the operations manually. Its straightforward if you expect/force everything to be either left or right associative. If you follow normal operator precedence (i.e. BEDMAS) then things become more complicated.
For the string you gave, assuming all operators are left-associative, you basically:
- parse the string left to right
- go until you see a non-number, so you read "1", "5", "+" and the characters up to the "+" is the left operand, the string "15" which you can convert to an int using "atoi"
- you now already know the operator
- continue looking for the next operand, "3", convert to int, perform the operation, and this value is the "new" left operand.
So you perform 15 + 3 = 18, then 18*2 = 36. As mentioned, this assumes left associativity for the operators. Doing right-associativity is just as easy. Things are quite complicated when you follow something like BEDMAS.
You could search for "shunting yard algorithm".
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
You could also go to the tutorial of Boost.Spirit and use that.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law