0

I'm trying to getting result from postfix. But it gives me wrong when subtraction, and don't know why. Please give many helps for c++ newbie.

I got two operands from stack. And tried subtraction "last popped" - "first popped".

/*pf_exp is postfix expression. String type*/
for (int i=0; i<pf_exp.length(); i++)
{
    int sub_result; // saving result.
    if (48 <= (int)pf_exp[i] && (int)pf_exp[i] <= 57)
    {
        operands.push((int)pf_exp[i] - 48);
    }
    else
    {
        /*operators is a stack<int> from '#include<stack>' storing operands.*/
        int operand2 = operands.top();
        operands.pop();
        int operand1 = operands.top();
        operands.pop();
        if(pf_exp[i] == '+')
        {
            sub_result = operand1 + operand2;
        }
        else if(pf_exp[i] == '-')
        {
            sub_result = operand1 - operand2;
        }
        else if(pf_exp[i] == '*')
        {
            sub_result = operand1 * operand2;
        }
        else if(pf_exp[i] == '/')
        {
            sub_result = operand1 / operand2;
        }
        operands.push(sub_result);
    }
}

I expect the output of "789--" to be "-10" but the actual output is "8".

vrintle
  • 5,501
  • 2
  • 16
  • 46
JWLee
  • 3
  • 1

1 Answers1

-1

You are probably thinking of the stack as a queue. You expect (7 - 8) - 9 = -10, but, since you are using a stack, the items added last are returned, so as Ben wrote, you are actually doing 7 - (8 - 9) = 8. Use a queue instead, and change the order of the operands to get what you actually wanted.

UPDATE

Sorry, my explanation did not take the postfix evaluation into account. As the comment states, it should always use a stack by definition. Nonetheless, my answer probably explains, why you were thinking of the wrong result.

Christoph Herold
  • 1,799
  • 13
  • 18
  • Postfix evaluation requires a stack, not a queue. – user207421 Mar 30 '19 at 08:36
  • I thought ```789--``` means ```7-8-9```. Am I thinking wrong about changing from infix to postfix? – JWLee Mar 31 '19 at 05:42
  • @JWLee: You must be thinking about it wrong, but it isn't that complicated. Step 1: Write canonical infix making all parentheses explicit: `(7-8)-9` Step 2: Move each operator to postfix position: `(78-)9-`. Step 3: Remove parentheses: `78-9-` – Ben Voigt Mar 31 '19 at 05:50
  • Note that the *reason* that postfix notation is defined to require a stack, is that with a queue you would always perform operations from left to right: `7↓8-9-` and `7↓8↓9--` are evaluated the same. With the stack, you can implement any precedence of operations, making it possible to evaluate expressions like `(a+b)/(c-d)` which simply would be impossible with a queue (with the stack, enter `a↓b+c↓d-/`). – Ben Voigt Mar 31 '19 at 05:57