parsing math expression in c++

Viewed 59194

I have a question about Parsing Trees:

I have a string (math expresion estring), for example: (a+b)*c-(d-e)*f/g. I have to parse that expression in a Tree:

class Exp{};
class Term: public Exp{
    int n_;
}

class Node: Public Exp{
    Exp* loperator_;
    Exp* roperator_;
    char operation; // +, -, *, /
}

What algorithm can I use to build a tree which represents the expresion string above?

6 Answers

I wrote a class to handle this back in the day. It's a little verbose and perhaps not the most efficient thing on the planet but it handles signed/unsigned integers, double, float, logical and bitwise operations.

It detects numeric overflow and underflow, returns descriptive text and error codes about syntax, can be forced to handle doubles as integers, or ignore signage, supports user definable precision and smart rounding and will even show its work if you set DebugMode(true).

Lastly...... it doesn't rely on any external libraries, so you can just drop it in.

Sample usage:

CMathParser parser;

double dResult = 0;
int iResult = 0;

//Double math:
if (parser.Calculate("10 * 10 + (6 ^ 7) * (3.14)", &dResult) != CMathParser::ResultOk)
{
    printf("Error in Formula: [%s].\n", parser.LastError()->Text);
}
printf("Double: %.4f\n", dResult);

//Logical math:
if (parser.Calculate("10 * 10 > 10 * 11", &iResult) != CMathParser::ResultOk)
{
    printf("Error in Formula: [%s].\n", parser.LastError()->Text);
}
printf("Logical: %d\n", iResult);

The latest version is always available via the CMathParser GitHub Repository.

Related