Made some small changes to convert and example 2-5.
[C-Programming-Examples.git] / calc_adv.c
blobdce8746086195b153f1b42ffeded1379d15bc5ff
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
5 #define MAXOP 100
6 #define NUMBER '0'
7 #define MAXVAL 100
8 #define BUFSIZE 100
10 int getop(char[]);
11 void push(double);
12 double pop(void);
13 void print_stack(void);
14 void reverse(void);
15 int getch(void);
16 void ungetch(int);
19 char buf[BUFSIZE];
20 int bufp = 0;
21 int sp = 0;
22 double val[MAXVAL];
24 int main()
26 int type;
27 double op2;
28 char s[MAXOP];
30 while((type = getop(s)) != EOF)
32 switch(type)
34 case NUMBER:
35 push(atof(s));
36 break;
37 case 'S':
38 case 's':
39 printf("Print Top of Stack\n");
40 print_stack();
41 break;
42 case 'R':
43 case 'r':
44 printf("Reverse Stack\n");
45 reverse();
46 break;
47 case '+':
48 push(pop() + pop());
49 break;
50 case '*':
51 push(pop() * pop());
52 break;
53 case '-':
54 op2 = pop();
55 push(pop() - op2);
56 break;
57 case '/':
58 op2 = pop();
59 if(op2 != 0.0)
60 push(pop() / op2);
61 else
62 printf("error: zero divisor\n");
63 break;
64 case '%':
65 op2 = pop();
66 if(op2 != 0.0)
68 push((int)(pop()) % (int)(op2));
69 } else {
70 printf("error: zero divisor\n");
72 break;
73 case '\n':
74 printf("\t%.8g\n", pop());
75 break;
76 default:
77 printf("error: unknown command %s\n", s);
78 break;
81 return 0;
84 /* push f onto value stack */
85 void push(double f)
87 if(sp < MAXVAL)
88 val[sp++] = f;
89 else
90 printf("error: stack full\n");
93 /* pop and return top value from stack */
94 double pop(void)
96 if(sp > 0)
97 return val[--sp];
98 else
100 printf("error: stack empty\n");
101 return 0.0;
105 /* reverse two vales at top of stack */
106 void reverse()
108 double temp1, temp2;
109 temp1 = pop();
110 temp2 = pop();
111 push(temp1);
112 push(temp2);
115 /* print top two values on stack */
116 void print_stack()
118 printf("%f\t%f\n", val[sp], val[sp-1]);
121 /* get next operator or numberic operand */
122 int getop(char s[])
124 int i, c;
126 while ((s[0] = c = getch()) == ' ' || c == '\t')
128 s[1] = '\0';
129 if(!isdigit(c) && c != '.')
130 return c;
131 i = 0;
132 if(isdigit(c))
133 while(isdigit(s[++i] = c = getch()))
135 if(c == '.')
136 while(isdigit(s[++i] = c = getch()))
138 s[i] = '\0';
139 if(c != EOF)
140 ungetch(c);
141 return NUMBER;
144 int getch(void)
146 return (bufp > 0) ? buf[--bufp] : getchar();
149 void ungetch(int c)
151 if(bufp >= BUFSIZE)
152 printf("ungetch: too many characters\n");
153 else
154 buf[bufp++] = c;