Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

No change reflecting outside the function even by passing reference:Infix to Postfix conversion

Problem:Given an infix expression. Convert the infix expression to postfix expression.

Infix expression:The expression of the form a op b. When an operator is in-between every pair of operands.

Postfix expression:The expression of the form a b op. When an operator is followed for every pair of operands.

Input:

The first line of input contains an integer T denoting the number of test cases. The next T lines contains an infix expression.The expression contains all characters and ^,*,/,+,-.

Output:

Output the infix expression to postfix expression.

Constraints: 1<=T<=100 1<=length of expression<=30

Example: Input: 2 a+b*(c^d-e)^(f+gh)-i A(B+C)/D

Output:

abcd^e-fgh*+^*+i- ABC+*D/

My Approach:

#include <iostream>
#include<string>
#include<stack>
using namespace std;
stack <char> sta;
int precedence(char a)
{
    if(a=='^') return 3;
    else if(a=='*'||a=='/')  return 2;
    else if(a=='+'||a=='-')  return 1;
    else return -1;
}
void infixtopostfix(string &a)
{
 for(int i=0;i<a.length();i++)
 {
     if((a[i]>='a'&&a[i]<='z')||(a[i]>='A'&&a[i]<='Z')) 
     {
         cout<<a[i];
     }
     else
     {   if(sta.empty()) sta.push(a[i]);
         else if(a[i]=='(')
         {
             sta.push('(');
         }
         else if(precedence(a[i])>precedence(sta.top()))
         {
             sta.push(a[i]);
         }
         else if(precedence(a[i])<=precedence(sta.top()))
         {
             while(precedence(a[i])<=precedence(sta.top()))
             {
             char y=sta.top();
             sta.pop();
             cout<<y;
             }
             sta.push(a[i]);
         }
         else
         {
             while(sta.top()!='(')
             {
               char y=sta.top();
             sta.pop();
             cout<<y;  
             }
             sta.pop();
         }
     }

 while(!sta.empty()){
  char y=sta.top();
            sta.pop();
            cout<<y;}
}}

int main() {
    int T;
    cin>>T;
    while(T--)
    {string a;
        cin>>a;
        infixtopostfix(a);
        cout<<"\n";
    }
    return 0;
}

My problem:

I am getting same answer as the input(no changes at all).I am wondering what's the mistake?

Comments