#include #include #include "stack4.h" class RPN : public Stack { int getop(int* n1, int* n2); public: void sum() { int n1, n2; if (getop(&n1, &n2)) push(n1+n2); } void sub() { int n1, n2; if (getop(&n1, &n2)) push(n1-n2); } void mul() { int n1, n2; if (getop(&n1, &n2)) push(n1*n2); } void div() { int n1, n2; if (getop(&n1, &n2)) push(n1/n2); } }; int RPN::getop(int* n1, int* n2) { if (empty()) { printf("empty stack!\n"); return 0; } *n2 = pop(); if (empty()) { push(*n2); printf("two operands needed!\n"); return 0; } *n1 = pop(); return 1; } int main(void) { RPN* s = new RPN; while (1) { char str[31]; int n; printf("> "); gets(str); if (sscanf(str, " %d", &n)==1) s->push(n); else { char c; sscanf(str, "%c", &c); switch(c) { case '+': s->sum(); break; case '-': s->sub(); break; case '*': s->mul(); break; case '/': s->div(); break; case 'q': delete s; return 0; default: printf("error\n"); } } int i = 0; StackIterator si(s); while (!si.end()) printf("%d:%6d\n", i++, si.next()); } }