How to parse expressions in C++

2019-02-02 18:20发布

I want to parse expressions such as res = ((a*(2+b))/c)+5.603+(6*(d^5)). I want to do it in c++ only.

3条回答
放我归山
2楼-- · 2019-02-02 18:55

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

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-02 18:59
做自己的国王
4楼-- · 2019-02-02 19:05

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.

查看更多
登录 后发表回答