diff options
-rw-r--r-- | ex4-3.c | 34 |
1 files changed, 27 insertions, 7 deletions
@@ -7,8 +7,11 @@ #define MAXVAL 100 int getop(char[]); + void push(double); double pop(void); +void clear(void); +double peek(void); // Naïve implementation of remainder operation double frem(double f1, double f2) { @@ -51,8 +54,10 @@ int main(void) { else printf("error: zero division attempted!\n"); break; + case '~': + clear(); case '\n': - printf("\t%.8g\n", pop()); + printf("\t%.8g\n", peek()); break; default: printf("unknown command %s\n", s); @@ -62,7 +67,6 @@ int main(void) { return 0; } - int sp; // Stack position double val[MAXVAL]; // Value stack void push(double f) { @@ -82,6 +86,18 @@ double pop(void) { } } +double peek(void) { + if (sp >= 0) { + return val[sp-1]; + } else { + printf("error, empty stack\n"); + return 0.0; + } +} + +void clear(void) { + sp = 0; +} int getch(void); void ungetch(int); @@ -110,16 +126,20 @@ int getop(char s[]) { #define BUFSIZE 100 -char buf[BUFSIZE]; // buffer for ungetch -int bufp = 0; // next free in buf +int buf = -2; int getch(void) { - return (bufp > 0) ? buf[--bufp] : getchar(); + if (buf != -2) { + int z = buf; + buf = -2; + return z; + } + return getchar(); } void ungetch(int c) { - if (bufp >= BUFSIZE) + if (buf != -2) printf("ungetch: buffer full\n"); else - buf[bufp++] = c; + buf = c; }
\ No newline at end of file |