简体   繁体   中英

Postfix to infix with stacks.

I'm working on a project to convert from post fix notation to, fully parenthesized infix notation. The issue I am having is, it prints/stores in the reverse order it prints out as:

 For line: QQ=
(Q=Q)


 For line: ABC*D+*
((D+(C*B))*A)


 For line: AB+CD+EF%G--*
(((G-(F%E))-(D+C))*(B+A))


 For line: NT^G*NN+#
((N+N)#(G*(T^N)))


 For line: A
A


 For line: ABC*D+*
((D+(C*B))*A)

my code that reads the data in is:

void ReadData(string inString, ifstream& in)
{
    if (in.is_open())
    {
        stack<string> postToIn;

        for (unsigned int i = 0; i< inString.length(); i++)
        {
            if ((inString[i] != '+') && (inString[i] != '-') && (inString[i] != '/') && (inString[i] != '#') &&
                (inString[i] != '*') && (inString[i] != '%') && (inString[i] != '^') && (inString[i] != '='))
            {
                string charac(1,inString[i]);

                postToIn.push(charac);
            }
            else
            {
                string temp = "";
                temp += "(";
                temp += postToIn.top();
                postToIn.pop();
                temp += inString[i];
                temp += postToIn.top();
                postToIn.pop();
                temp += ")";
                postToIn.push(temp);
            }           
        }


        while (!postToIn.empty())
        {
            cout << postToIn.top();
            postToIn.pop();
        }
        cout << endl;       
    }
}

I can't tell where in my code it is reversing it. I know the stacks are first out/ last in. Any help would be greatly appreciated.

The stack top will have the most recent operand which is what you want on the right side. The current implementation puts it on the left side of the operator.

            string temp = "";
            string temp2 = "";
            temp += "(";
            temp2 += postToIn.top(); // This is the recent operand. This needs to go on the right of the operator in infix notation
            postToIn.pop();
            temp += postToIn.top();
            postToIn.pop();
            temp += inString[i];
            temp += temp2;
            temp += ")";
            postToIn.push(temp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM