2 * Exercise 4-4. Add commands to print the top element of the stack without
3 * popping, to duplicate it, and to swap the top two elements. Add a command to
8 #include <stdlib.h> /* for atof() */
10 #define MAXOP 100 /* max size of operand or operator */
11 #define NUMBER '0' /* signal that a number was found */
16 double printtop(void);
21 /* reverse Polish calculator */
27 while ((type = getop(s)) != EOF) {
47 printf("error: zero divisor\n");
52 push((int) pop() % (int) op2);
54 printf("error: zero divisor\n");
57 printf("\t%.8g\n", printtop());
61 printf("error: can't duplicate\n");
65 printf("error: swap failed, stack needs two numbers\n");
71 printf("\t%.8g\n", pop());
74 printf("error: unknown command %s\n", s);
80 #define MAXVAL 100 /* maximum depth of val stack */
82 int sp = 0; /* next free stack position */
83 double val[MAXVAL]; /* value stack */
85 /* push: push f onto value stack */
86 void push (double f) {
90 printf ("error: stack full, can't push %g\n", f);
93 /* pop: pop and return top value from stack */
98 printf("error: stack empty\n");
103 /* printtop: print the top value of the stack without popping it */
104 double printtop(void) {
108 printf("error: stack empty\n");
113 /* duplicate: duplicate the top value of the stack
114 * return 1 if successful, 0 on failure */
115 int duplicate(void) {
118 } else if (sp >= MAXVAL) {
127 /* swap: swap the top two values of the stack
128 * return 1 if successful, 0 on failure */
131 int temp = val[sp-1];
132 val[sp-1] = val[sp-2];
139 /* clear: clear the stack */
149 /* getop: get next operator or numeric operand */
150 int getop(char s[]) {
152 while ((s[0] = c = getch()) == ' ' || c == '\t')
156 /* negative number or minus */
158 s[++i] = c = getch();
159 if (!isdigit(c) && c != '.') {
164 if (!isdigit(c) && c != '.')
165 return c; /* not a number */
166 if (isdigit(c)) /* collect integer part */
167 while (isdigit(s[++i] = c = getch()))
169 if (c == '.') /* collect fraction part */
170 while (isdigit(s[++i] = c = getch()))
180 char buf[BUFSIZE]; /* buffer for ungetch */
183 /* get a (possibly pushed back) character */
185 return (bufp > 0) ? buf[--bufp] : getchar();
188 /* push character back on input */
189 void ungetch(int c) {
191 printf("ungetch: too many characters\n");