2014-10-13

So for a school project we need to convert a infix expression to a postfix expression.
Infix being like what we read in normal mathematics: ( 6 + 2) * 5 - 8 / 4 and postfix having the operator after the numbers: 6 2 + 5 * 8 4 / -

This is a problem from the Deitel 7th Edition C++ Learn to Program book. (Late objects version). Chapter 20 Problem 12. We have been given permission to use the C++ standard library stack class as opposed to creating our own like in the book.

The book gives the following instructions:
The program should read the expression into string infix and create a postfix expression in string postfix. The algorithm for creating a postfix expression is as follows:

1.) Push a left parenthesis onto the stack.

2.) Append a right parentheses to the end of infix.

3.) While the stack is not empty. Read infix from left to right and do the following.

If the current character in infix is a digit, copy it to the next element of postfix.
If the current character in infix is a left parenthesis push it onto the stack
If the current character in infix is an operator,

Pop any operators(if there are any) at the top of the stack while they have equal or higher precedence than the current operator and insert the popped operators into postfix. Push the current character in infix onto the stack.

If the current character is a right parenthesis:

Pop operators from the top of the stack and insert them into postfix until a left parenthesis is at the top of the stack.
Pop and discard the left parenthesis from the stack.

I tried my best to do all of this and the code is below. Upon testing it, I got some strange output.

Input: ( 6 + 2) * 5 - 8 / 4

Output: )(6)+)*)5)-8)/)4

Should Be: 6 2 + 5 * 8 4 / -

Further testing gets some even wilder results

Input: pw

Output: )pw

Should Be: Invalid Input: you lose.

I'm sorry I can't narrow it down more and the question is huge. I've been slaving at this for hours and I don't know whats up. I think it's because I'm unknowingly misusing on of the standard library functions/classes.

Additional Informations:
This is file is included by another file which reads in strings until "s" is inputted by the user. It then calls the function pofix.
I'm using whatever compiler Visual Studio 2013 uses.

Show more