// File: postfixeval.cpp
// Program that uses a stack to evaluate postfix expressions

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

int PostfixEval(const string & expr);

int main ()
{
   string expr;
   int result;

   cout << "Enter a postfix expression consisting of single digits and arithmentic operators:\n";
   getline(cin, expr);

   result = PostfixEval(expr);
   cout << "The result of this expression is: " << result << endl;
}

// 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
//          and the basic arithmetic operators
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
