#include #include #include #include #define DEL 1 #define VAR 2 #define NR 3 char token[80]; char tok_type; char *prog; double vars[26]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; void asg(int *ans); void exp(int *ans); void atom(int *ans); void get_token(void); int isdelim(char c); int find_var(char *s); void main(void) { int ans; char *p; p=malloc(100); do { prog=p; printf("enter expression: "); gets(prog); asg(&ans); printf("answer is: %d\n",ans); } while (*p); } void asg(int *ans) { int temp, slot; char op; get_token(); if(tok_type==VAR) { slot=toupper(*token)-'A'; get_token(); get_token(); exp(ans); vars[slot]=*ans; return; } exp(ans); } void exp(int *ans) { char op; int temp; atom(ans); while((op=*token)=='+' || op=='-') { get_token(); atom(&temp); switch(op) { case '-': *ans=*ans-temp; break; case '+': *ans=*ans+temp; break; } } } void atom(int *ans) { switch(tok_type) { case VAR: *ans=find_var(token); get_token(); return; case NR: *ans=atoi(token); get_token(); return; } } void get_token(void) { char *temp; tok_type=0; temp=token; *temp='\0'; if (!*prog) return; while(isspace(*prog)) ++prog; if (strchr ("+-*/=()", *prog)) { tok_type=DEL; *temp++=*prog++;} else if(isalpha(*prog)) { while(!isdelim(*prog)) *temp++=*prog++; tok_type=VAR;} else if(isdigit(*prog)) { while(!isdelim(*prog)) *temp++=*prog++; tok_type=NR; } *temp='\0'; } isdelim(char c) { if (strchr (" +-/*=()", c) || c==9 || c=='\r' || c==0) return 1; return 0; } int find_var(char *s) { if(!isalpha(*s)) return 0; return vars[toupper(*token)-'A']; }