'Conversion of Infix expression to Postfix
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
