diff options
author | Martin Ashby <martin@ashbysoft.com> | 2022-11-21 21:09:30 +0000 |
---|---|---|
committer | Martin Ashby <martin@ashbysoft.com> | 2022-11-21 21:09:30 +0000 |
commit | cc66f02855428590fa4172aa6a8b88fa0a8109bf (patch) | |
tree | 21978129ced4311b8a0e8d8e88c398e80290cc00 | |
parent | 50534766e09667a9c23c1f167dca92f5d4fd0f27 (diff) | |
download | learn-c-cc66f02855428590fa4172aa6a8b88fa0a8109bf.tar.gz learn-c-cc66f02855428590fa4172aa6a8b88fa0a8109bf.tar.bz2 learn-c-cc66f02855428590fa4172aa6a8b88fa0a8109bf.tar.xz learn-c-cc66f02855428590fa4172aa6a8b88fa0a8109bf.zip |
have just a single char pushback
-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 |