Path: blob/master/languages/cprogs/Ex_4.11_getch_static.c
1240 views
/* modify getop so that it does not need to use ungetch: Hint: static int lastc */12#include<stdio.h>3#include<stdlib.h>45#define MAXOP 1006#define NUMBER '0'78int getop(char []);9void push(double);10double pop(void);1112/* reverse polish calculator */1314int main(void)15{16int type;17double op2;18char s[MAXOP];1920while((type = getop(s)) != EOF)21{22switch(type)23{24case NUMBER:25push(atof(s));26break;27case '+':28push(pop()+pop());29break;30case '*':31push(pop()*pop());32break;33case '-':34op2=pop();35push(pop()-op2);36break;37case '/':38op2=pop();39if(op2 != 0.0)40push(pop()/op2);41break;42case '\n':43printf("\t%.8g\n",pop());44break;45default:46printf("error: unknown command %s\n",s);47break;48}49}50return 0;51}525354#define MAXVAL 1005556int sp = 0;57double val[MAXVAL];5859/* push : push f onto value stack */6061void push(double f)62{63if(sp < MAXVAL)64val[sp++] = f;65else66printf("error: stack full,can't push %g\n",f);67}6869/* pop: pop and return top value from stack */7071double pop(void)72{73if(sp > 0)74return val[--sp];75else76{77printf("error: stack empty\n");78return 0.0;79}80}8182#include<ctype.h>8384int getch(void);8586/* getop: get next operator or numeric operand */8788int getop(char s[])89{90int c,i;91static int lastc = 0;9293if(lastc == 0)94c = getch();95else96{97c = lastc;98lastc = 0;99}100101while((s[0]=c) == ' ' || c == '\t')102c = getch();103104s[1]='\0';105106if(!isdigit(c) && c!= '.')107return c;108109i = 0;110if(isdigit(c))111while(isdigit(s[++i] =c=getch()))112;113if(c=='.')114while(isdigit(s[++i] =c=getch()))115;116s[i]='\0';117118if(c!=EOF)119lastc=c;120121return NUMBER;122}123124#define BUFSIZE 100125126char buf[BUFSIZE];127int bufp;128129int getch(void)130{131return (bufp > 0) ? buf[--bufp] : getchar();132}133134135136