/* * This is a simple post-fix expression evaluator. (I needed to exercise the * our latest stack, and got tired of completely meaningless stack * manipulation.) Input is integers, operators +, -, *, /, or the period * character as an end marker. This is evaluated as a postfix expression * with minimal error checking. */ #include #include #include #include "lnkstack.h" using namespace std; int main() { // Stack of integers. Stack is; // Read the input. char op; while(cin >> op) { // See what we got. if(op == '.') { // Halt char. break; } else if(isdigit(op)) { // Digit. Unget it, read the number, and push it // on the stack. cin.unget(); int val; cin >> val; is.push(val); continue; } else if(string("+-*/").find(op) != string::npos) { // Operator, pop the operands. int a,b; if(!is.pop(b)) break; if(!is.pop(a)) break; // Push the operation result in place of the operands. switch(op) { case '+': is.push(a+b); break; case '-': is.push(a-b); break; case '*': is.push(a*b); break; case '/': is.push(a/b); break; } } else { // Just what it says. cout << "Bad char " << op << endl; } } // If there's a result, print it. If the stack is empty, just // whine about it. int res; if(is.pop(res)) cout << "Value: " << res << endl; cout << "Stack has " << is.size() << " elements at exit." << endl; }