0

I understand that the stoi() function might suit the needs of only an integer value, however I need to convert the following string into an actual arithmetic operation. For example:

"3 + 7 * 4 - 2" into 3 + 7 * 4 - 2

where if I had to assign that to a variable the result will be 29.

Code4life
  • 95
  • 4
  • 3
    No. But there are many libraries out there which handle simple algebraic problems. – user6556709 May 16 '19 at 10:32
  • You need to parse your string and then evaluate it – Moia May 16 '19 at 10:33
  • 1
    No there is no support for parsing arithmetic expressions in the standard library. You could try implementing the Shunting-yard-algorithm, or search for libraries that parse arithmetic expressions – Petok Lorand May 16 '19 at 10:33
  • One could use an interpreted language like Lua, Python, JavaScript or R to parse this type of expression. Especially Lua is supposed to be easily integrated in into a C project. – Martin Ueding May 16 '19 at 10:57

1 Answers1

2

In short : No.

How to handle this truly depends on how the string was created in the first place. Is this some user providing some simple input on stdin and you catch it with std::cin ?

If it's really a simple expression (no parenthesis etc.), you could read from stdin an int, a char, an int, a char, an int etc... and just parse the char as the operator.

I've come accross the Shunting-Yard Algorithm when I had similar a issue and it seemed to be quite what I wanted.

You could also implement some grammar. It's really rewarding when it works but this is a lot of work and overkill. See parsing math expression in c++. You'll have way better comments than mine there with code examples.

SOKS
  • 190
  • 3
  • 11