How to pass a simple math operation stored in a string to system then get the output

Hello,
I have a ustring that stores a simple operation for example :
"2+3/4"
The problem now is that i am using Gtkmm and the entry support only ustring not an int, and now i want to pass the operation to the system then i want to get the output, is there any possible way to do it or another way that is simple ?
Unless you want to use some third-party library that is able to parse and evaluate "arithmetic expressions" you will have to implement this yourself. This means that you will have to split the given expression (string) in separate tokens, figure out which of these tokens are operators and which are operands. Numeric operands then need to be parsed as integers (or floats). Finally you can proceed to doing the actual math. Depending on how "flexible" you want to be on which arithmetic expressions you accept, this can be quite a complex task...

Maybe have a look at the TinyExpr library, so you don't have to re-invent the wheel:
https://github.com/codeplea/tinyexpr#short-example
Last edited on
Thanks for responding,
What if i use a vector to store numbers and another one to store operations, then i will figure out sn algorithm to solve it is it right ?
you are moving the problem, sort of. Either the user must enter values a specific way (eg value, operator, value, operator, ...) or you will get out of sync or messed up. A simple answer WILL work as long as you keep the input simple, though. By forcing the user to put the values in with a simple format, it is 'already parsed' and you can as you said just store them and use them without trying to unravel it. Only you know if that is appropriate to your needs.

note that if you allow division you have to work in doubles (or deal with the remainders and write a bunch of extra code for all that). eg 3/4 is zero in integer space.
Last edited on
There is also precedence of operators. 2+3/4 should act like 2+(3/4).
Will you handle parentheses? User could write "simple" (2+3)/4.

Point is an expression is a binary tree. The root node performs the '+' operation to its children (operands) '2' and '3/4'. The latter is operator '/' that has two children: '3' and '4'. Parsing creates the tree and then evaluates it, starting from deepest branches.

The (2+3)/4 is a different tree, although it has the same leaves (2, 3, and 4) and same internal nodes (+ and /).

IIRC, Stroustrup uses expression parsing as example in his C++ book(s).
Last edited on
If you are going to recognise precedence, then you are going to have to first transform the expression into something resembling Reverse Polish using techniques such as Shunting Yard, Recursive Descent etc. This is w whole topic in itself and there's loads of info about these on the Internet.

Unless there is further parsing involved, then the Shunting Yard should be sufficient.
Topic archived. No new replies allowed.