Added tutorial 3-5. Converts int to string of chars with alt base.
[C-Programming-Examples.git] / calc.c
blob66408e2951c02b826f51a29350f296567e2868ae
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);
14 int main()
16 int type;
17 double op2;
18 char s[MAXOP];
20 while((type = getop(s)) != EOF)
22 switch(type)
24 case NUMBER:
25 push(atof(s));
26 break;
27 case '+':
28 push(pop() + pop());
29 break;
30 case '*':
31 push(pop() * pop());
32 break;
33 case '-':
34 op2 = pop();
35 push(pop() - op2);
36 break;
37 case '/':
38 op2 = pop();
39 if(op2 != 0.0)
40 push(pop() / op2);
41 else
42 printf("error: zero divisor\n");
43 break;
44 case '\n':
45 printf("\t%.8g\n", pop());
46 break;
47 default:
48 printf("error: unknown command %s\n", s);
49 break;
52 return 0;
58 int sp = 0;
59 double val[MAXVAL];
62 /* push f onto value stack */
63 void push(double f)
65 if(sp < MAXVAL)
66 val[sp++] = f;
67 else
68 printf("error: stack full\n");
72 /* pop and return top value from stack */
73 double pop(void)
75 if(sp > 0)
76 return val[--sp];
77 else
79 printf("error: stack empty\n");
80 return 0.0;
86 int getch(void);
87 void ungetch(int);
89 /* get next operator or numberic operand */
90 int getop(char s[])
92 int i, c;
94 while ((s[0] = c = getch()) == ' ' || c == '\t')
96 s[1] = '\0';
97 if(!isdigit(c) && c != '.')
98 return c;
99 i = 0;
100 if(isdigit(c))
101 while(isdigit(s[++i] = c = getch()))
103 if(c == '.')
104 while(isdigit(s[++i] = c = getch()))
106 s[i] = '\0';
107 if(c != EOF)
108 ungetch(c);
109 return NUMBER;
112 char buf[BUFSIZE];
113 int bufp = 0;
115 int getch(void)
117 return (bufp > 0) ? buf[--bufp] : getchar();
121 void ungetch(int c)
123 if(bufp >= BUFSIZE)
124 printf("ungetch: toomany characters\n");
125 else
126 buf[bufp++] = c;