/* Expression Parser */ /* Martian */ #include #include #include #include "stack.h" int IsOp(char *data); void parse(char *data, StackDat *tokens[]) { char newdata[128]; char c; char token[7]; StackDat *temp; int i=0, j=0, l=0, t=0; /* printf("data=\"%s\"\n",data);*/ for(i=0; data[i]; i++) if(data[i]!=9 && data[i]!=32) newdata[j++]=data[i]; newdata[j]=0; /* printf("newdata=\"%s\"\n",newdata);*/ for(i=0;newdata[i];i++) { c=newdata[i]; /* printf("\nc=%c ",c);*/ if(c>='0' && c<='9') { /* It's a number */ token[l++]=c; /* printf("Adding to token. ");*/ } else { /* Must be an operator */ if(l) { /* printf("Storing token ");*/ token[l]=0; temp=(StackDat *)malloc(sizeof(StackDat)); temp->val=atoi(token); /* printf("val=%d ",temp->val);*/ temp->type=0; tokens[t++]=temp; token[0]=0; l=0; } token[0]=c; token[1]=0; if(c=='*') if(newdata[i+1]=='*') { token[1]='*'; token[2]=0; i++; } temp=(StackDat *)malloc(sizeof(StackDat)); temp->type=1; temp->val=IsOp(token); /* printf("Storing token. val=%d ",temp->val);*/ tokens[t++]=temp; token[0]=0; } } if(l) { /* printf("Storing token ");*/ token[l]=0; temp=(StackDat *)malloc(sizeof(StackDat)); temp->val=atoi(token); /* printf("val=%d ",temp->val);*/ temp->type=0; tokens[t++]=temp; token[0]=0; l=0; } /* printf("\n");*/ tokens[t]=NULL; } int IsOp(char *data) { if(!strcmp(data,"(")) return 1; else if(!strcmp(data,")")) return 2; else if(!strcmp(data,"+")) return 3; else if(!strcmp(data,"-")) return 4; else if(!strcmp(data,"*")) return 5; else if(!strcmp(data,"/")) return 6; else if(!strcmp(data,"**")) return 7; else if(!strcmp(data,"~")) return 8; return 0; }