// Function: PostfixEval()
// Receives: an postfix expression in a string
// Returns: the value of the postfix expression
// Assumes: the postfix expression consists of single digit numerals

#include <stack>
#include <string>
using namespace std;

int PostfixEval (const string & expr)
{
   int operand1, operand2, result;
   char token;
   stack<int> operandStack;

   for (int i = 0; i < expr.length(); i++)
   {
      token = expr[i];
      if ((token >= '0') && (token <= '9'))
      {
         operand1 = token - '0';  // convert digit character to number
         operandStack.push (operand1);
      }  // if an operand
      else if ((token == '+') || (token == '-') || 
               (token == '*') || (token == '/'))
      {
         operand2 = operandStack.top();  // right operand comes off first
         operandStack.pop();
         operand1 = operandStack.top();  // then the left operand
         operandStack.pop();
         switch (token)
         {
            case '+': result = operand1 + operand2;
                      break;
            case '-': result = operand1 - operand2;
                      break;
            case '*': result = operand1 * operand2;
                      break;
            case '/': result = operand1 / operand2;
                      break;
         }  // end computing result
         operandStack.push(result);
      }  // end if an operator
      // else skip everything else
   }  // end for

   return (operandStack.top());
}  // end PostfixEval
