user9468830
user9468830

Reputation: 17

c++ postfix evaluation problems

stack<int> s;
int main() {
    string exp;
    cout << "Enter postfix expression: ";
    getline(cin, exp);
    int calc = evaluatePosfix(exp);
    cout << calc << endl;
}

int evaluatePosfix(string exp) {
    for (int i = 0; i < exp.length(); i++) {
        if (exp[i] == ' ' || exp[i] == ',') {
            continue;
        }
        if (isNum(exp[i])){
            int operand = 0;
            while(i < exp.length() && isNum(exp[i])) {
                operand = (operand*10) + (exp[i] - '0');
                i++;
            }
            i--;
            cout << operand << "&&" << endl;
            s.push(operand);
        }

        else if(isOperator(exp[i])) {
            int operand2 = s.top(); s.pop();
            int operand1 = s.top(); s.pop();
            int result = performOperation(operand1, operand2, exp[i]);
            s.push(result);
        }

        //cout << s.top() << " $$$" << endl;
    }

    return s.top();
}

bool isOperator(char c) {
    if (c == '+' || c == '-' || c == '*' || c == '/') {
        return true;
    }
    return false;
}

bool isNum(char c) {
    if (c >= '0' || c <= '9') {
        return true;
    }
    return false;
}

int performOperation(int operand1, int operand2, char operation) {
    if (operation == '+') {
        return operand1 + operand2;
    }
    else if (operation == '-') {
        return operand1 + operand2;
    }
    else if (operation == '*') {
        return operand1 * operand2;
    }
    else if (operation == '/') {
        return operand1 / operand2;
    }
    else {
        cout << "Error" << endl;
        return -1;
    }
}

Post-fix is not being evaluated properly. When I type in 22+ it returns 215 instead of 4. When the program detects an operator, it should pop the 2 elements in the stack but for some reason it doesn't do that. When the performOperation is called, the operation does not occur, therefor nothing gets pushed onto the stack.

Upvotes: 0

Views: 367

Answers (2)

user9950573
user9950573

Reputation: 41

@meat is correct you need to read the input stream (file or cin) as tokens.

#include <cstring>
char token[6];

while (stream >> token)
{
    if (token[0] == '=') // what ever the end char is
    {
        //process and evaluate expression
    }
    else if (isdigit(*token)) // will pass a 4 byte int not just 0-9
    {
        // process a number
    }
    else if (ispunct(token0])) // is 1 byte math symbol + - * / 
    {
        // process a math symbol
    }

that should solve the 0-9 reading issues.

Upvotes: 0

meat
meat

Reputation: 619

If 22+ is supposed to evaluate to 4 then this section is the culprit:

while(i < exp.length() && isNum(exp[i])) {
    operand = (operand*10) + (exp[i] - '0');
    i++;
}

Your code is written to handle numbers greater than 10 but your example suggests that you only support single digits.

Upvotes: 1

Related Questions