This is the code for reverse polish calculator. I know how it works, but im confused by this exercise related to it:
"Suppose that there will never be more then one char of pushback. Modify getch and ungetch accordingly".
Isnt that actually true, that there will never be more then one character of pushback? Ungetch is used only in getop function and after the pushback the function returns a value to main. So basicaly, never can it happen that more then 1 character is pushed back, yet the code in the book is written in a way that pushback characters are being stored in an array?
I also have one question: How to fix ungetch and getch so they handle EOF's correctly? Is it enough to just add a check in getch() if the readed char is EOF, and if so, return EOF value in main which then terminates the while loop?
(the code is seperated into 5 source files, so you can easily see all the functions)
Code:
#include "calc.h"
#define MAXOP 100
int main(int argc, char *argv[])
{
int type;
double op2;
char s[MAXOP];
while((type = getop(s)) != EOF)
{
switch(type) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
if((op2 = pop()) != 0)
push(pop() / op2);
else
printf("zero divisor\n");
break;
case '\n':
printf("\t%g\n", pop());
break;
default:
printf("unknown command\n");
break;
}
}
getchar();
return 0;
}
Code:
#include <ctype.h> /* isdigit */
#include "calc.h"
/* get a operand or operator */
int getop(char s[])
{
int i, c;
while((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if(!isdigit(c) && c!='.')
return c;
i = 0;
if(isdigit(c))
while(isdigit(s[++i] = c = getch()))
;
if(c == '.')
while(isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if(c!=EOF)
ungetch(c);
return NUMBER;
}
Code:
#include "calc.h"
#define MAXVAL 100
double val[MAXVAL];
int sp = 0;
void push(double c)
{
if(sp < MAXVAL)
val[sp++] = c;
else
printf("stack full\n");
}
double pop()
{
if(sp > 0)
return val[--sp];
else {
printf("stack empty\n");
return 0.0;
}
}
Code:
#include "calc.h"
#define MAXBUF 100
int buf[MAXBUF];
int bufp = 0;
int getch()
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) //stores the temp char
{
if(bufp >= MAXBUF)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
Code:
/* headers */
#include <stdio.h>
#include <stdlib.h>
#define NUMBER '0'
int getop(char []);
void push(double);
double pop();
int getch();
void ungetch(int);