/** * rpn.c - a simple Reverse Polish Notation calculator that reads its * input from standard input. */ #include #include #include #include // +-----------+------------------------------------------------------ // | Constants | // +-----------+ // The capacity of the stack #define STACK_CAPACITY 16 // +------+----------------------------------------------------------- // | Main | // +------+ int main (int argc, char *argv[]) { int stack[STACK_CAPACITY] = { 0 }; // The stack of numbers for RPN evaluation int top = 0; // The top of the stack. That is, the first // empty space on the stack. Also the number // of items on the stack. int done = 0; // A flag that indicates whether or not we're // done processing input. int i; // The next input value. int ch; // A character we're reading int scanok; // The result of scanf while (!done) { i = 0; if ((scanok = (scanf (" p%n",&i) != EOF)) && (i >= 1)) { if (top == 0) printf ("NO VALUE\n"); else printf ("%d\n", stack[top-1]); } else if (scanok && (scanok = (scanf (" +%n",&i) != EOF)) && (i >= 1)) { top--; if (top <= 0) { printf ("ERROR: Stack underflow\n"); return EXIT_FAILURE; } stack[top-1] = stack[top-1] + stack[top]; } // "+" else if (scanok && (scanok = (scanf (" -%n",&i) != EOF)) && (i >= 1)) { top--; if (top <= 0) { printf ("ERROR: Stack underflow\n"); return EXIT_FAILURE; } stack[top-1] = stack[top-1] - stack[top]; } // "-" else if (scanok && (scanok = (scanf (" *%n",&i) != EOF)) && (i >= 1)) { top--; if (top <= 0) { printf ("ERROR: Stack underflow\n"); return EXIT_FAILURE; } stack[top-1] = stack[top-1] * stack[top]; } // "*" else if (scanok && (scanok = (scanf (" /%n",&i) != EOF)) && (i >= 1)) { top--; if (top <= 0) { printf ("ERROR: Stack underflow\n"); return EXIT_FAILURE; } stack[top-1] = stack[top-1] / stack[top]; } // "/" else if (scanok && (scanok = (scanf (" negate%n",&i) != EOF)) && (i >= 1)) { if (top <= 0) { printf ("ERROR: Stack underflow\n"); return EXIT_FAILURE; } stack[top-1] = -stack[top-1]; } else if (scanok && (scanf(" %d", &i) == 1)) { if (top >= STACK_CAPACITY) { printf ("ERROR! Stack overflow\n"); return EXIT_FAILURE; } stack[top] = i; top++; } else { if (! scanok) { done = 1; break; } ch = getchar (); if (ch == EOF) done = 1; else if ((ch == '\n') || (ch == ' ') || (ch == '\n')) ; // Skip whitespace else printf ("Invalid input: '%c'\n", ch); } } // while return EXIT_SUCCESS; } // main