user3019579
user3019579

Reputation: 71

Infix to Postfix - Deleting Parenthesis

Having trouble getting the parenthesis to pop from the string. I enter an infix expression such as (A+B)*C and would like to get AB+C*. Instead, I get (AB)+C*. Any help would be greatly appreciated.

 string Postfx::convertToPostfix(Postfx C,string in)
    {
    stack<char> S;
    string postfx = "";



    for (int i = 0; i<in.length();i++)
    {
        if (in[i] == ' ' || in[i] == ',') continue;

        else if ((in[i]) == '+' || in[i] == '-' || in[i] == '/' || in[i] == '*')
        {
            while (!S.empty() && S.top() != '(' && C.precedence(S.top(), in[i]))
            {
                postfx += S.top();
                S.pop();
            }
            S.push(in[i]);
        }

        else if ((in[i]) != '+' || in[i] != '-' || in[i] != '/' || in[i] != '*')
        {
            postfx += in[i];
        }

        else if (in[i] == '(')
        {
            S.push(in[i]);
        }
        else if (in[i] == ')')
        {
            while (!S.empty() && S.top() != '(')
            {
                postfx += S.top();
                S.pop();
            }
            S.pop();
        }
    }

    while (!S.empty()) {
        postfx += S.top();
        S.pop();
    }

    return postfx;
}

Upvotes: 1

Views: 228

Answers (2)

user207421
user207421

Reputation: 310859

Don't append the parentheses to the output. They're only in the stack to guide your actions. I don't know where you got this code but you need to take a good look at the Dijkstra Shunting-yard algorithm. Your version doesn't match it at several points, and some of it doesn't even make sense:

if (in[i] != '+' || in[i] != '-' || in[i] != '/' || in[i] != '*')

Upvotes: 0

Petr
Petr

Reputation: 9997

I think that your

else if ((in[i]) != '+' || in[i] != '-' || in[i] != '/' || in[i] != '*')

line catches brackets as well, so

else if (in[i] == '(')

and below never gets executed.

I think you should move

else if ((in[i]) != '+' || in[i] != '-' || in[i] != '/' || in[i] != '*')

to be the last option in the chained if.

Moreover, this if catches absolutely any symbol (because any symbol is either not equal to '+', or not equal to '-'). You need to replace || by &&; but if you will anyway have this if the last in chained if, you need no condition there at all, something like:

if ((in[i] == ' ')|| ...
else if ((in[i] == '+')|| ...
else if (in[i] == '(') ...
else if (in[i] == ')') ...
else postfx += in[i]; // no condition here

P.S. Also if you wrap the initial expression in brackets:

in = "(" + in + ")"

before the loop, you will not need the final while (!S.empty()) loop.

Upvotes: 1

Related Questions