How to parse expressions in C++
I want to parse expressions suc开发者_如何学Ch as res = ((a*(2+b))/c)+5.603+(6*(d^5)). I want to do it in c++ only.
Have a look at the "Available C++ Libraries" FAQ
Stroustrup explains how you'd evaluate expressions like ((1*(2+3))/4)+5.603+(6*(11^5))
. Basically, you build an evaluation tree for all subexpressions.
Your example has three extra steps. In parsing, you have to note the variables a
, and in evaluating you have to replace the variables with their current values. Finally, you need to assign the result to variables.
You can use a std::map<std::string, double>
to hold the variable names and values.
There is a thorough treatment of a possible approach to here:
http://www.ibm.com/developerworks/library/j-w3eval/index.html
The code is in java, but is quite portable to C++.
精彩评论