Say I have a string that looks like this “234+22-76=”. How can i parse the sting into numbers and operators and then calculate the result? In this instance 180.
C++ doesn't have an "eval" function, so you have to build your own expression parser, or more likely, find one you can adapt to your needs.
If you're really just doing addition and subtraction, you can just iterate through your string using atoi (or atol) as you go and look for the operators.
May well be better to find a different way - what are you trying to do?
It is when you come to write this you find out how convoluted this sort of way of writing down expressions is.
On the other hand if you use reverse Polish notation becomes easy because there is no need to suspend the operation. After each step you get something to do with the symbol or number you have just got. This was the basics of the language called Forth. So for your expression you would write it as:-
234 22 + 76 - .
Which means, if it is a number push it onto the stack. If it is an operator then apply that to the first two numbers on the stack and push the result to the top of the stack. The period simply removes the number an top of the stack and prints it.
I have purchased a touchscreen and am playing around with it. I have adapted a script which uses input to dial a number and changed the scrren layout to look like a calculator. I can input my digits and when I press the = sign I am left with a string like the on in my example, which I tought should be quite easy to parse.
Another possibility might be to push the digits into an array and convert them into numbers when the operators are pressed.
It just seems a lot of work when I already have a string with all of the information I need........
It just seems a lot of work when I already have a string with all of the information I need.
Yes it is which is why reverse polish was invented.