简体   繁体   中英

Are there any functions in the C++ library that converts a string into an arithmetic operation?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM