cplusplus
.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
Forum
Beginners
Convert mathematical operations from str
Convert mathematical operations from string to integer?
Jun 6, 2014 at 9:00am UTC
TheBasix
(4)
If I have input string s = "5+3"; and I have to calculate this and return INT which is equal to 8. How can I do that?
Jun 6, 2014 at 9:51am UTC
MiiNiPaa
(8886)
You want to parse math expression. Here is example of algorithm using stacks to parse arithmetic expressions:
http://en.wikipedia.org/wiki/Shunting-yard_algorithm
and its implementations:
http://www.smccd.net/accounts/hasson/C++2Notes/ArithmeticParsing.html
http://pastebin.com/gSsZjMh2
http://habrastorage.org/getpro/habr/comment_images/532/3b4/a47/5323b4a47b1039df5b46fb310f711720.png
If you want to add even more complex functions you might need to build an AST:
http://en.wikipedia.org/wiki/Abstract_syntax_tree
http://stackoverflow.com/questions/1721553/how-to-construct-an-abstract-syntax-tree
Or you can use one of the existing parsers:
https://www.google.ru/search?q=math+expression+parser+c%2B%2B
Last edited on
Jun 6, 2014 at 9:51am UTC
Jun 6, 2014 at 10:06am UTC
TheBasix
(4)
Thats seems a little to complicated for this task. But how do I take each number from that string?
Jun 6, 2014 at 10:11am UTC
MiiNiPaa
(8886)
But how do I take each number from that string?
Either use stringstreams (
http://www.cplusplus.com/reference/sstream/istringstream/
) and work with string like with normal stream (as std::cin), or extract substring containing number and apply stoi() function.
Topic archived. No new replies allowed.