c - Infix notation to postfix notation using stack -
i trying convert infix notation postfix notation using stack. have written following code giving me error:
/users/apple/desktop/infix.c|49|error: expected expression
and unable find error. please me correct code.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #define max 100 char st[max]; int top = -1; void push(char st[],char); char pop(char st[]); void infixtopostfix(char source[],char target[]); int getpriority(char); int main(){ char infix[100],postfix[100]; printf("enter infix expression"); fflush(stdin); gets(infix); strcpy(postfix,""); infixtopostfix(infix,postfix); printf("\nthe corresponding postfix expression is:"); puts(postfix); return 0; } void infixtopostfix(char source[],char target[]){ int i=0,j=0; char temp; strcpy(target,""); while(source[i]!='\0') { if(source[i]=='(') { push(st,source[i]); i++; } else if(source[i]==')') { while((top!=-1)&&(st[top]!='(')) { target[j]=pop(st); j++; } if(top==-1) { printf("\nincorrect syntax"); exit(1); } temp=pop(st); i++; else if((isdigit(source[i]))||(isalpha(source[i])) { target[j]=source[i]; j++; i++; } else if(source[i]=='+'||source[i]=='- '||source[i]=='*'||source[i]='/'||source[i]=='%d') { while((top!=-1)&&(st[top]!='(')&&(getpriority(st[top])>getpriority(source[i]))) { target[j]=target[i]; i++; } push(st,source[i]); i++; } else{ printf("\nincorrect expression"); exit(1); } } while((top!=-1)&&(st[top]!='(')) { target[j]=pop(st); j++; } target[j]='\0'; } } int getpriority(char op) { if(op=='/'||op=='*'||op=='%'||op=='%') return 1; else if(op=='+'||op=='-') return 0; } void push(char st[],char val) { if(top==max-1) printf("overflow"); else{ top++; st[top]=val; } } char pop(char st[]) { char val=' '; if(top==-1) printf("underflow"); else{ val=st[top]; top--; } return val; }
many problems, important 1 being
else if((isdigit(source[i]))||(isalpha(source[i]))
lacks closing parentheses, coding style makes difficult notice
else if ((isdigit(source[i]) != 0) || (isalpha(source[i]) != 0))
and don't use gets()
it's deprecated, in case
fgets(infix, sizeof(infix), stdin);
would work, , have benefit of preventing buffer overflow.
Comments
Post a Comment