/* * Postfix (reverse Polish) calculator * uses switch and no arithmetic/math functions */ #include #include #include #include "stack.h" /* * maximum length of input line */ #define MAXLINE 1000 /* * the main routine */ int main(void) { char line[MAXLINE]; /* input line */ char *l; /* used to get input characters */ int v1, v2; /* operands for current operation */ /* * process the input line by line */ while(fgets(line, MAXLINE, stdin) != NULL){ /* * got line; now walk it char by char */ for(l = line; *l; l++){ /* skip white space */ if (isspace(*l)) continue; /* now act based on the character you see */ switch(*l){ case '0': case '1': case '2': /* number */ case '3': case '4': case '5': case '6': case '7': case '8': case '9': push(*l - '0'); break; case '+': /* add */ if (pop(&v1) == 0) continue; if (pop(&v2) == 0) continue; push(v2 + v1); break; case '-': /* subtract */ if (pop(&v1) == 0) continue; if (pop(&v2) == 0) continue; push(v2 - v1); break; case '*': /* multiply */ if (pop(&v1) == 0) continue; if (pop(&v2) == 0) continue; push(v2 * v1); break; case 'p': /* print stack */ if (pop(&v1) == 0) continue; printf("%d\n", v1); push(v1); break; case 'P': /* print stack */ printstack(); break; default: /* unknown */ fprintf(stderr, "Unknown operand/operator '%c'\n", *l); break; } } } /* * all done! */ return(0); }