Infix to postfix expression. Don't work
function definitions in classes are all right.
problem is in output.
error may be in handling array of char.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
using namespace std;
# include <iostream>
# include <ctype.h>
# include "list.h"
bool prec(char x, char y);//user defined function to check precedence of operators
int main()//main starts
{
Stack<char> s1;
char z,a,array[30];
int i=0;
do
{
cout<<"Enter expression character by character or $ to show postfix expression: ";
cin>>z;
if(z!='$')
{
if((isalpha(z)==true) || (isdigit(z)==true))
{array[i]=z;i++;}
else if(z=='(')// encounter (
{s1.push(z);}
else if(z==')')
{
array[i++]=s1.pop();//i++;
s1.pop();
if(s1.isEmpty()!=true)
{array[i]=s1.pop();i++;}
}
else if((z=='+' || z=='-' || z=='*' || z=='/' || z=='^') && (s1.isEmpty()==true))
{s1.push(z);}
else if((z=='+' || z=='-' || z=='*' || z=='/' || z=='^') && (s1.getTop()=='('))
{ s1.push(z);}
else if((z=='+' || z=='-' || z=='*' || z=='/' || z=='^') && (s1.isEmpty()==false))
{
a=s1.getTop();
if(prec(z,a)==true)
{array[i]=z;i++;}
else
{array[i]=s1.pop();i++;}
}
}
}while(z!='$');
//print exression after conversion to postfix
cout<<"size of array is: "<<i<<"\n\n";
cout<<"\n\n\t\tEXPRESSION in POSTFIX form is: ";
for(int j=0;j<i;j++)
{
cout<<array[i];
}
cout<<"\n\n\n";
system("pause");
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
//function to check precedence
bool prec(char x, char y)
{
if(x=='(' || x==')')
{
return true;
}
if(x=='*')
{
if(y=='(' || y==')')
return false;
else
return true;
}
if(x=='/')
{
if(y=='(' || y==')')
return false;
else
return true;
}
if(x=='^')
{
if(y=='(' || y==')')
return false;
else
return true;
}
if(x=='+')
{
if(y=='(' || y==')')
return false;
if(y=='*' || y=='/' || y=='^')
return false;
else
return true;
}
if(x=='-')
{
if(y=='(' || y==')')
return false;
if(y=='*' || y=='/' || y=='^')
return false;
else
return true;
}
}
|
Last edited on
Topic archived. No new replies allowed.