开发者

How to parse expressions in C++

开发者 https://www.devze.com 2023-03-25 20:44 出处:网络
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\" FAQStroustrup explains how you\'d eval

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++.

0

精彩评论

暂无评论...
验证码 换一张
取 消