i have this code that converts infix expression to postfix expression but the problem is that when the values are two or more digits the evaluation is wrong
can anyone help me please :)
#include<iostream.h>
#include<stdio.h>
#include <math.h>
#define SIZE 100
class Stack
{
private:
int top;
char s[SIZE];
public:
Stack()
{
top=0;
}
int isEmpty()
{
return top<=0;
}
int isFull()
{
return top>=SIZE;
}
char pop();
void push(char x);
~Stack()
{
}
};
char Stack::pop()
{
if(!isEmpty())
{
top--;
return s[top];
}
else
{
return NULL;
}
}
void Stack::push(char x)
{
if(!isFull())
{
s[top]=x;
top++;
}
else
{
cout<<"Stack over flow"<<endl;
}
}
int isOperator(char x)
{
if(x=='^'||x=='/'||x=='*'||x=='+'||x=='-'||x=='%')
{
return 1;
}
else
{
return 0;
}
}
int pr(char x)
{
if(x=='^')
return 100;
else
if(x=='*'||x=='/'||x=='%')
return 90;
else
if(x=='+'||x=='-')
return 80;
else
if(x=='(')
return 1;
else
return 0;
}
double EVALUATION(int w,int e,char u )
{
double x=0;
if(u=='/')
{
x=e/w;
}
else
if(u=='^')
{
x= pow(e,w);
}
else
if(u=='*')
{
x=e*w;
}
else
if(u=='%')
{
x=e%w;
}
else
if(u=='+')
{
x=e+w;
}
else
if(u=='-')
{
x=e-w;
}
return x;
}
void main()
{
Stack s;
Stack eval;
char ex[100];
gets(ex);
char postfix[100];
char *q=postfix;
int i=0;
char *p=ex;
cout<<"postfix= ";
while(*p)
{
char t=*p++;
if(t=='(')
s.push(t);
else
if(t==')')
{
char x=s.pop();
while(x!='('&&!s.isEmpty())
{
cout<<x;
postfix[i]=x;
i++;
x=s.pop();
}
}
else
if(!isOperator(t))
{
cout<<t;
postfix[i]=t;
i++;
}
else
if(isOperator(t)&&s.isEmpty())
{
s.push(t);
}
else
if(isOperator(t)&&!s.isEmpty())
{
char v=s.pop();
int flag=0;
while(pr(t)<=pr(v)&&flag==0)
{
cout<<v;
postfix[i]=v;
i++;
if(!s.isEmpty())
v=s.pop();
flag=1;
}
if(pr(t)>pr(v))
{
s.push(v);
}
s.push(t);
}
}
while(!s.isEmpty())
{
char x=s.pop();
cout<<x;
postfix[i]=x;
i++;
}
postfix[i]=NULL;
cout<<endl;
while(*q!=NULL)
{
char u=*q++;
if(!isOperator(u))
{
eval.push(u);
}
else if(isOperator(u))
{
char first= eval.pop();
char sec= eval.pop();
int x= first -'0' ;
int y= sec -'0';
double result=EVALUATION(x,y,u);
char z=(int)result+48;
eval.push(z);
}
}
char d=eval.pop();
double final=d-48;
cout<<"Resault= "<<final;
if(!eval.isEmpty())
{
cout<<"syntax Error";
}
cout<<endl;
}
thanks