Search code examples
c++parsingpostfix-notation

How does one convert '+' to +, '*' to *, etc


I'm writing a function that reads a postfix expression in the form of a string and computes it accordingly.

Is there a simple way to convert the character of an arithmetic operator to the arithmetic operator itself in C++?


Solution

  • Assuming that this is for the classic RPN programming exercise, the simplest solution is to use a switch statement:

    char op = ...    
    int lhs = ...
    int rhs = ...
    int res = 0;
    switch(op) {
        case '+':
            res = lhs + rhs;
        break;
        case '-':
            res = lhs - rhs;
        break;
        case '*':
            res = lhs * rhs;
        break;
        case '/':
            res = lhs / rhs;
        break;
        case '%':
            res = lhs % rhs;
        break;
    }