// minimal comments, postfix.cc, Owen Astrachan, 9/3/93 // modified 9/16/94, modified 1/27/96 for stack/class changes #include #include // for isspace #include // for exit #include "apstack.h" int Operate(char op,const int & left, const int & right); int main() { apstack s; int left,right; char c; while (cin.get(c)) // one char at a time { if (isdigit(c)) { cin.putback(c); // back onto stream for reading cin >> left; // read number, push it s.push(left); } else if (isspace(c)) // skip { continue; } else // operate char: '*', etc., push { s.pop(right); s.pop(left); s.push(Operate(c,left,right)); } } // get result (on top of stack) if (s.isEmpty()) { cerr << "malformed postfix, stack empty" << endl; exit(1); } s.pop(left); // final answer if (!s.isEmpty()) { cerr << "malformed postfix, stack not empty" << endl; } else { cout << "result = " << left << endl; } } int Operate(char c,const int & left, const int & right) // precondition: c in ['+','*','-','/'], represents corresponding op // postcondition: returns left op right { int result; switch(c) { case '+': result = left+right; break; case '*': result = left*right; break; case '-': result = left-right; break; case '/': result = left/right; break; default: result = 0; break; } return result; }