Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_4.10_calculator_getline.c
1240 views
1
/* Revise the Calculator program to use the getline instead of getch and ungetch */
2
3
#include<stdio.h>
4
#include<stdlib.h> /* for atof() */
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 notation 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%.9g\n",pop());
45
break;
46
default:
47
printf("error: unknown command %s\n",s);
48
break;
49
}
50
}
51
return 0;
52
}
53
54
#define MAXVAL 100 /* maximum depth of the val stack */
55
56
int sp = 0;
57
double val[MAXVAL];
58
59
/* push : push f onto value stack */
60
61
void push(double f)
62
{
63
if(sp < MAXVAL)
64
val[sp++] = f;
65
else
66
printf("error: stack full,can't push %g\n",f);
67
}
68
69
/* pop: pop and return top values from stack */
70
71
double pop(void)
72
{
73
if(sp > 0)
74
return val[--sp];
75
else
76
{
77
printf("error: stack empty \n");
78
return 0.0;
79
}
80
}
81
82
83
/* using getline instead of getch and ungetch */
84
85
#include<ctype.h>
86
#define MAXLINE 100
87
88
int mgetline(char line[],int limit);
89
90
int li= 0; /* input line index */
91
char line[MAXLINE]; /* one input line */
92
93
/* getop: get next operator or numeric operand */
94
95
int getop(char s[])
96
{
97
int c,i;
98
99
if(line[li] == '\0')
100
if(mgetline(line,MAXLINE) == 0)
101
return EOF;
102
else
103
li =0;
104
105
while((s[0] = c = line[li++]) == ' ' || c == '\t')
106
;
107
108
s[1] = '\0';
109
110
if(!isdigit(c) && c!= '.')
111
return c;
112
113
i = 0;
114
115
if(isdigit(c))
116
while(isdigit(s[++i] = c = line[li++]))
117
;
118
if( c == '.')
119
while(isdigit(s[++i] = c = line[li++]))
120
;
121
122
s[i] = '\0';
123
124
li--;
125
126
return NUMBER;
127
}
128
129
int mgetline(char s[],int lim)
130
{
131
int i,c;
132
133
for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
134
s[i] =c;
135
136
if(c=='\n')
137
s[i++] =c;
138
139
s[i]='\0';
140
141
return i;
142
}
143
144
145
146
147