From cc66f02855428590fa4172aa6a8b88fa0a8109bf Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Mon, 21 Nov 2022 21:09:30 +0000 Subject: have just a single char pushback --- ex4-3.c | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) (limited to 'ex4-3.c') diff --git a/ex4-3.c b/ex4-3.c index 7de79fb..ca5739a 100644 --- a/ex4-3.c +++ b/ex4-3.c @@ -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 -- cgit v1.2.3-ZIG