Evaluating arithmetic expressions from string in C++

I'm searching for a simple way to evaluate a simple math expression from an string, like this:

3*2+4*1+(4+9)*6

I just want + and * operations plus ( and ) signs. And * has more priority than +.


Solution 1:

One can try : http://partow.net/programming/exprtk/index.html

  1. very simple
  2. only need to include "exprtk.hpp" to your source code.
  3. you can change the value of variables of the expression dynamically.
  4. good starting point: http://partow.net/programming/exprtk/code/exprtk_simple_example_01.cpp

Solution 2:

I think you're looking for a simple recursive descent parser.

Here's a very simple example:

const char * expressionToParse = "3*2+4*1+(4+9)*6";

char peek()
{
    return *expressionToParse;
}

char get()
{
    return *expressionToParse++;
}

int expression();

int number()
{
    int result = get() - '0';
    while (peek() >= '0' && peek() <= '9')
    {
        result = 10*result + get() - '0';
    }
    return result;
}

int factor()
{
    if (peek() >= '0' && peek() <= '9')
        return number();
    else if (peek() == '(')
    {
        get(); // '('
        int result = expression();
        get(); // ')'
        return result;
    }
    else if (peek() == '-')
    {
        get();
        return -factor();
    }
    return 0; // error
}

int term()
{
    int result = factor();
    while (peek() == '*' || peek() == '/')
        if (get() == '*')
            result *= factor();
        else
            result /= factor();
    return result;
}

int expression()
{
    int result = term();
    while (peek() == '+' || peek() == '-')
        if (get() == '+')
            result += term();
        else
            result -= term();
    return result;
}

int _tmain(int argc, _TCHAR* argv[])
{

    int result = expression();

    return 0;
}