Click here to Skip to main content
15,395,897 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C++
#include <iostream>
#include <stack>

class InfixToPostfix
{

public:

    InfixToPostfix(const std::string &expression) : expression_(expression) { }

    int getPrecedenceOfOperators(char);

    std::string convertInfixToPostfix();

private:
    std::string expression_;

};

int InfixToPostfix::getPrecedenceOfOperators(char ch)
{
    if(ch == '+' || ch == '-')
        return 1;
    if(ch == '*' || ch == '/')
        return 2;
    if(ch == '^')
        return 3;
    else
        return 0;
}

std::string InfixToPostfix::convertInfixToPostfix()
{
    std::stack <char> stack1;
    std::string infixToPostfixExp = "";
    int i = 0;
    while(expression_[i] != '\0')
    {
        //if scanned character is open bracket push it on stack
        if(expression_[i] == '(' || expression_[i] == '[' || expression_[i] == '{')
            stack1.push(expression_[i]);

            //if scanned character is opened bracket pop all literals from stack till matching open bracket gets poped
        else if(expression_[i] == ')' || expression_[i] == ']' || expression_[i] == '}')
        {
            if(expression_[i] == ')')
            {
                while(stack1.top() != '(')
                {
                    infixToPostfixExp = infixToPostfixExp + stack1.top();
                    stack1.pop();
                }
            }
            if(expression_[i] == ']')
            {
                while(stack1.top() != '[')
                {
                    infixToPostfixExp = infixToPostfixExp + stack1.top();
                    stack1.pop();
                }
            }
            if(expression_[i] == '}')
            {
                while(stack1.top() != '{')
                {
                    infixToPostfixExp = infixToPostfixExp + stack1.top();
                    stack1.pop();
                }
            }
            stack1.pop();
        }
            //if scanned character is operator
        else if(expression_[i] == '+' || expression_[i] == '-' || expression_[i] == '*' || expression_[i] == '/' || expression_[i] == '^')
        {
            //very first operator of expression is to be pushed on stack
            if(stack1.empty()) {
                stack1.push(expression_[i]);

            } else{
                /*
                 * check the precedence order of instack(means the one on top of stack) and incoming operator,
                 * if instack operator has higher priority than incoming operator pop it out of stack&put it in
                 * final postifix expression, on other side if precedence order of instack operator is less than i
                 * coming operator, push incoming operator on stack.
                 */
                if(getPrecedenceOfOperators(stack1.top()) >= getPrecedenceOfOperators(expression_[i]))
                {
                    infixToPostfixExp = infixToPostfixExp + stack1.top();
                    stack1.pop();
                    stack1.push(expression_[i]);
                }
                else
                {
                    stack1.push(expression_[i]);
                }
            }
        }
        else
        {
            //if literal is operand, put it on to final postfix expression
            infixToPostfixExp = infixToPostfixExp + expression_[i];
        }
        i++;
    }

    //poping out all remainig operator literals & adding to final postfix expression
    if(!stack1.empty())
    {
        while(!stack1.empty())
        {
            infixToPostfixExp = infixToPostfixExp + stack1.top();
            stack1.pop();
        }
    }

    return infixToPostfixExp;

}

int main()
{
    InfixToPostfix p("a+b*c/d-q");
    std::cout << "\nPostfix expression      : " << p.convertInfixToPostfix();
}


What I have tried:

Please help me to convert it. I have tried plenty of things but it still giving errors. I will be grate full for any help.
Posted
Updated 16-May-21 20:12pm
v2
Comments
Rick York 16-May-21 23:06pm
   
Nope. You need to do your own work. For this code, it appears you will need to make your own stack library. That should be fun. The string work looks interesting too. You might find strcat to be a useful function.

This is not a code conversion service: we are not here to translate code for you.
Even if we did, what you would end up with would not be "good code" in the target language – they are based on very different frameworks, and what makes something work in one language does not always "translate" directly into another.
So what you end up with is very poor code, that is difficult if not impossible to maintain, that can’t be upgraded nicely, and that will cause you immense headaches if the original is changed. And it’ll be a nightmare to debug if it doesn’t work "straight out of the box".
Instead, use the source code as a specification for a new app written in and for the target language / framework and write it from scratch using the original as a "template". You will get a much, much better result that will save you a lot of time in the long run.

In addition, many of the elements that - rather poor - C++ code uses aren't available in C at all, so they would need to be written specially. That's more work than sitting down and doing your own homework would have been in the first place, plus you would need more advanced coding skills than the original task required ...
   
The bulk of the work is the stack class conversion: while the C++ standard library gently provides it, the C library does not provide similar functionality.
Now I wonder if someone in the web could help on that... (How to implement a stack in C using an array[^]).
   
Comments
Mehreen Saleem 17-May-21 2:37am
   
I have implemented the slack library in C. But please help me in converting this code. We will deal with all kind of brackets and basic operations which includes ^ ( precedence 3), *,/(precedence 2), +,-(precedence 1). Any help will be appreciated.
Here is the algorithm.
Create a function that takes an infix expression as input and converts it to a postfix expression. It should
take pointers to two strings as input; one containing the infix expression, and second to which this
function will write the postfix expression i.e. the declaration should be
void infixToPostfix(char *infix, char *postfix, int str_size);
The algorithm is as follows:
Iterate over the infix expression’s string. For each character c,
• If c is an operand, concatenate it with the postfix expression.
• If c is an operator, check if top of stack, say m, is an operator. If so, check if the operator
precedence of m is higher or equal to the operator precedence of c; if yes, concatenate m with
postfix expression, and pop it from the stack. Keep doing this until the top of stack is not an
operator with operator precedence higher or equal to the operator precedence of c. Then push
c on the stack.
• After completely processing input expression, TopAndPop remaining operators from stack and
concatenate each with postfix expression, in the order they are popped.
You can perform string concatenation using strcat().
Rick York 17-May-21 11:51am
   
YOU need to do this work. Exercises like this is how you learn. We've learned this stuff so it is of no help to us. We also have no interest in enabling more inept programmers because there are far too many in the world already. The only way you are going to learn this is to do your own work. Converting someone else's work doesn't help anyone, least of all YOU.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900