-
postfix calculator
i am trying a postfis calculator so far i wrote
Code:
#include<stdio.h>
#include<string.h>
int st[15],top=0;
void push(int);
int pop(void);
void print();
main()
{int ch;
char o;
char st[15],temp[15][5];
float arr[15];
int i=0,j=0,r=0,c=0,l=0,t;
printf("\nEnter Expression");
fgets(st,15,stdin);
printf("\nEX=%s",st);
l=strlen(st);
while(i<l)
{ one: if(st[i]=='+' || st[i]=='-' || st[i]=='*' || st[i]=='/')
{o=st[i];
switch(o)
{case '+': t=pop();printf("\nadding %d pushing ",t);
push(pop()+t);
i++;goto one;//break;
case '-': t=pop();
push(t-pop());
break;
case '*':t=pop();
push(t*pop());
break;
case '/':t=pop();
//pop();
push(pop()/t);
default:break;
}
}
else
while(st[i]!='\0' && st[i]!=' ')
{
temp[r][c]=st[i];
i++;
c++;
}temp[r][c]='\0';
printf("\npushing %d",atoi(temp[r]));
push(atoi(temp[r]));
r++;
i++;c=0;
}
print();
}
void push(int i)
{puts("\ninpush");
if(top==15)
{printf("\nStack full");
return;
}
st[top]=i;
printf("\nst=%d,top=%d",st[top],top);
top++;
}
int pop()
{ if(top==-1)
{ printf("\nUnder");}
//print("\npop=%d",st[top]);
return(st[--top]);
}
void print()
{
top--;
printf("\n\n\nResult=%d\n\n",st[top]);
}
iam not getting the right result though in out out ican see the result getting pushed in stack but the it pushes 0 and result is 0.
what else can i do??
Thnx.
-
I think it's better to write separate function for parsing. K&R book has example postfix calculator.
And fix your indentation.It's hard to read your code. http://www.csd.uoc.gr/~hy150b/spring...ple/index.html
I hope you learn something from it...