Below is the program i have written to convert a infix expression to postfix. It does give an output but its not always the right one. For example if we input the expression A B*C-D/F G , the expected output is ABC* DF/G - but rather the program outputs AB C*D-F/G . What is the problem in the program.
#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
int prec(char oper){
if(oper == '^')
return 3;
else if(oper == '*' || '/')
return 2;
else if(oper == ' ' || '-')
return 1;
else
return -1;
}
string itp(string s){
stack<char> stack;
string output = "";
int num = s.length();
for(int i = 0 ; i < num ; i ){
char ch = s[i];
if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z')||(ch>='0' && ch<='9'))
output = output ch;
else if(ch == '(')
stack.push('(');
else if(ch == ')'){
while(stack.top()!='('){
output = output stack.top();
stack.pop();
}
stack.pop();
}
else{
while(!stack.empty() && prec(s[i]) <= prec(stack.top())){
output = output stack.top();
stack.pop();
}
stack.push(ch);
}
}
while (!stack.empty()) {
output = output stack.top();
stack.pop();
}
return output;
}
int main(){
string question;
cout<<"Enter the infix expression : ";
cin >> question;
cout<<endl<<"Postfix expression : "<<itp(question);
return 0;
}
CodePudding user response:
Here:
else if(oper == '*' || '/')
you are using ||
wrongly. If you consider operator precedence (https://en.cppreference.com/w/cpp/language/operator_precedence) you will see that ==
has higher rank than ||
, hence it is parsed as
else if( (oper == '*') || '\')
The first part will evaluate to true
or false
but as \
is not equal to 0
, it will be true
always, hence in total the condition is true
always.
What you want is
else if( oper=='*' || oper=='\')