/* ** $Id: rpn.c 739 2008-02-09 00:58:20Z phf $ */ #include #include #include #include #include "stack.h" #define SIZE 128 bool is_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } void handle_print(void) { if (size() > 0) { printf("top: %d\n", top()); } else { puts("error: nothing to print since stack is empty"); } } void handle_integer(int i) { if (size() < capacity()) { push(i); } else { printf("error: can't push %d since stack is full\n", i); } } void handle_operator(char c) { if (size() >= 2) { int right = top(); pop(); int left = top(); pop(); switch (c) { case '+': push(left+right); break; case '-': push(left-right); break; case '*': push(left*right); break; case '/': push(left/right); break; default: // should be impossible to get here, but we better make sure! :-) assert(false); break; } } else { puts("error: need two values to perform operation"); } } int main() { char buffer[SIZE]; while (fgets(buffer, SIZE, stdin) != NULL) { char op = buffer[0]; if (op == '.') { handle_print(); } else if (is_operator(op)) { handle_operator(op); } else { // assume a string denoting an int int value = strtol(buffer, NULL, 10); handle_integer(value); } } return EXIT_SUCCESS; }