Monday, October 20, 2014

Convertiong Infix to Postfix code - in C++

#include <iostream>
#include <stack>
#include <string>
#include <cctype>
using namespace std;

class infix_to_postfix
{

protected:
    string exp;
    string infixexp;
    stack<char> charstack;

    bool prcd(char a, char b)
    {
        return a > b;
    }

   public:
            infix_to_postfix(string str)
            {
                 exp = str;
            }

            void push_to_stack()
            {
                  for(int i = 0; exp[i]; ++i)
                  {
                         if(exp[i] == ' ')
                             continue;

                   if(isalnum(exp[i]))
                   {
                         infixexp += exp[i];
                   }

             else
             {
                      while(!charstack.empty() && prcd(exp[i], charstack.top()))
                      {
                              infixexp += charstack.top();
                               charstack.pop();
                      }

                              charstack.push(exp[i]);
             }
        }

        while(!charstack.empty())
        {
            infixexp += charstack.top();
            charstack.pop();
        }
    }

    string print()
    {
        return infixexp;
    }


   
};

class evaluate {
public:
    evaluate(string str)
    {
        exp = str;
    }

    void peform()
    {
        int res;

        for(int i = 0; i < exp.length(); i++)
        {
            if(isalnum(exp[i]))
            {
                nums.push(exp[i] - '0');
            }
            else
            {
                if(!nums.empty())
                {
                    int a = nums.top();
                    nums.pop();
                    int b = nums.top();
                    nums.pop();

                    res = doit(b, exp[i], a);
                }
                nums.push(res);
            }
        }
    }

    int retres()
    {
        return nums.top();
    }

protected:
    string exp;
    stack<int> nums;

private:
    int doit(int a, char c, int b)
    {
        switch(c)
        {
        case '+':
            return a + b;
            break;

        case '-':
            return a - b;
            break;

        case '*':
            return a * b;
            break;

        case '/':
            return a / b;
            break;
        }
    }
};

int main()
{
    string infixstr;
    infix_to_postfix itop("5 * 2 + 3 * 1 - 9");

    itop.push_to_stack();
    infixstr = itop.print();

    cout << infixstr << endl;

    evaluate ev(infixstr);
    ev.peform();

    int res = ev.retres();

    cout << res << endl;

    return 0;
}

No comments:

Post a Comment