Path: blob/master/languages/cprogs/Ex_4.10_calculator_getline.c
1240 views
/* Revise the Calculator program to use the getline instead of getch and ungetch */12#include<stdio.h>3#include<stdlib.h> /* for atof() */45#define MAXOP 1006#define NUMBER '0'78int getop(char []);9void push(double);10double pop(void);1112/* reverse polish notation 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%.9g\n",pop());44break;45default:46printf("error: unknown command %s\n",s);47break;48}49}50return 0;51}5253#define MAXVAL 100 /* maximum depth of the val stack */5455int sp = 0;56double val[MAXVAL];5758/* push : push f onto value stack */5960void push(double f)61{62if(sp < MAXVAL)63val[sp++] = f;64else65printf("error: stack full,can't push %g\n",f);66}6768/* pop: pop and return top values from stack */6970double pop(void)71{72if(sp > 0)73return val[--sp];74else75{76printf("error: stack empty \n");77return 0.0;78}79}808182/* using getline instead of getch and ungetch */8384#include<ctype.h>85#define MAXLINE 1008687int mgetline(char line[],int limit);8889int li= 0; /* input line index */90char line[MAXLINE]; /* one input line */9192/* getop: get next operator or numeric operand */9394int getop(char s[])95{96int c,i;9798if(line[li] == '\0')99if(mgetline(line,MAXLINE) == 0)100return EOF;101else102li =0;103104while((s[0] = c = line[li++]) == ' ' || c == '\t')105;106107s[1] = '\0';108109if(!isdigit(c) && c!= '.')110return c;111112i = 0;113114if(isdigit(c))115while(isdigit(s[++i] = c = line[li++]))116;117if( c == '.')118while(isdigit(s[++i] = c = line[li++]))119;120121s[i] = '\0';122123li--;124125return NUMBER;126}127128int mgetline(char s[],int lim)129{130int i,c;131132for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)133s[i] =c;134135if(c=='\n')136s[i++] =c;137138s[i]='\0';139140return i;141}142143144145146147