Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_4.11_getch_static.c
1240 views
1
/* modify getop so that it does not need to use ungetch: Hint: static int lastc */
2
3
#include<stdio.h>
4
#include<stdlib.h>
5
6
#define MAXOP 100
7
#define NUMBER '0'
8
9
int getop(char []);
10
void push(double);
11
double pop(void);
12
13
/* reverse polish calculator */
14
15
int main(void)
16
{
17
int type;
18
double op2;
19
char s[MAXOP];
20
21
while((type = getop(s)) != EOF)
22
{
23
switch(type)
24
{
25
case NUMBER:
26
push(atof(s));
27
break;
28
case '+':
29
push(pop()+pop());
30
break;
31
case '*':
32
push(pop()*pop());
33
break;
34
case '-':
35
op2=pop();
36
push(pop()-op2);
37
break;
38
case '/':
39
op2=pop();
40
if(op2 != 0.0)
41
push(pop()/op2);
42
break;
43
case '\n':
44
printf("\t%.8g\n",pop());
45
break;
46
default:
47
printf("error: unknown command %s\n",s);
48
break;
49
}
50
}
51
return 0;
52
}
53
54
55
#define MAXVAL 100
56
57
int sp = 0;
58
double val[MAXVAL];
59
60
/* push : push f onto value stack */
61
62
void push(double f)
63
{
64
if(sp < MAXVAL)
65
val[sp++] = f;
66
else
67
printf("error: stack full,can't push %g\n",f);
68
}
69
70
/* pop: pop and return top value from stack */
71
72
double pop(void)
73
{
74
if(sp > 0)
75
return val[--sp];
76
else
77
{
78
printf("error: stack empty\n");
79
return 0.0;
80
}
81
}
82
83
#include<ctype.h>
84
85
int getch(void);
86
87
/* getop: get next operator or numeric operand */
88
89
int getop(char s[])
90
{
91
int c,i;
92
static int lastc = 0;
93
94
if(lastc == 0)
95
c = getch();
96
else
97
{
98
c = lastc;
99
lastc = 0;
100
}
101
102
while((s[0]=c) == ' ' || c == '\t')
103
c = getch();
104
105
s[1]='\0';
106
107
if(!isdigit(c) && c!= '.')
108
return c;
109
110
i = 0;
111
if(isdigit(c))
112
while(isdigit(s[++i] =c=getch()))
113
;
114
if(c=='.')
115
while(isdigit(s[++i] =c=getch()))
116
;
117
s[i]='\0';
118
119
if(c!=EOF)
120
lastc=c;
121
122
return NUMBER;
123
}
124
125
#define BUFSIZE 100
126
127
char buf[BUFSIZE];
128
int bufp;
129
130
int getch(void)
131
{
132
return (bufp > 0) ? buf[--bufp] : getchar();
133
}
134
135
136