Suyash Mohan
Suyash Mohan

Reputation: 493

How to parse expressions in C++

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.

Upvotes: 11

Views: 1721

Answers (3)

MSalters
MSalters

Reputation: 180215

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.

Upvotes: 1

bcr
bcr

Reputation: 1328

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

Upvotes: 0

Nikki Locke
Nikki Locke

Reputation: 2951

Have a look at the "Available C++ Libraries" FAQ

Upvotes: 4

Related Questions