Infix to Postfix

#include<bits/stdc++.h>
using namespace std;
int priority(char ch)
{
    if(ch == '^')
        return 3;
    else if(ch == '/' || ch == '*')
        return 2;
    else if(ch == '+' || ch == '-')
        return 1;
    else
        return 0;
}

string converter(string infix)
{
    string postfix = "";
    stack<char>s;
    char ch;
    int i, l = infix.size();

    for(i=0;i<l;i++)
    {
        ch = infix[i];

        if(ch == '(')
            s.push('(');

        else if(ch == ')')
        {

            while(!s.empty() && s.top() != '(')
            {
                postfix = postfix + s.top();
                s.pop();
            }

            if(!s.empty() && s.top() == '(')
                s.pop();
        }

        else
        {
            int p = priority(ch);

            if(p == 0)
                postfix = postfix + ch;

            else if(s.empty())
                s.push(ch);

            else
            {

                while(!s.empty() && s.top() != '(' && p <= priority(s.top()))
                {
                    postfix = postfix + s.top();
                    s.pop();
                }

                s.push(ch);
            }
        }
    }

    while(!s.empty())
    {
        postfix = postfix + s.top();
        s.pop();
    }

    return postfix;
}

double calculate(int a, int b, char ch)
{
    if(ch == '+')
        return a+b;
    else if(ch == '-')
        return a-b;
    else if(ch == '*')
        return a*b;
    else if(ch == '/')
        return a/b;
    else if(ch == '^')
    {
        return pow(a, b);
    }
}

double reader(string postfix)
{
    char ch;
    stack<double>s;
    int c;
    int i, l = postfix.size();
    for(i=0;i<l;i++)
    {
        ch = postfix[i];

        if(ch >= '0' && ch <= '9')
            s.push(ch - '0');

        else
        {
            double a , b;
            b = s.top();
            s.pop();
            a = s.top();
            s.pop();

            double c = calculate(a, b, ch);
            s.push(c);
        }
    }

    return s.top();
}

int main()
{
    string pfix, infix;

    cout << "Enter A Infix : ";
    getline(cin , infix);

    pfix = converter(infix);

    double result = reader(pfix);

    cout << endl << "Result :: " << result << endl;

    return 0;
}

Comments