CS-183
C++ Program #1
Infix to Postfix Expressions
Date Assigned: Friday, March 8th, 2002
The purpose of this assignment is to use existing classes in C++ to implement a simple text conversion program. The text to be converted consists of arithmetic expressions in infix form. The goal of the converter is to produce a corresponding postfix expression that exactly reproduces the infix expression. For example, the following infix expression is converted to postfix below:
Infix: a + b * c / d – e
Postfix: a b c * d / + e –
The operators in these expressions have their usual precedence:
Operator |
Precedence |
|
*, / |
2 |
|
+, - |
1 |
For the sake of simplicity, the operands are all single letter identifiers. The higher precedence operators are always evaluated before the lower precedence ones. Thus, the correct order of evaluation for the expression above is:
1. t1 = b * c
2. t2 = t1 / d
3. t3 = a + t2
4. ans = t3 – e
In order to perform the conversion, the following rules must be followed:
1. Operators are stored in a stack (a last-in, first-out data structure).
2. Operands are simply passed through to the postfix expression, where they are added to the end of the postfix expression being generated.
3. When stacking operators, only higher precedence operators can be stacked on top of lower precedence ones.
4. If an operator entering the stack has lower precedence than the top operator, then we remove the top operator and append it to the end of the postfix expression.
5. By the same token, if an operator entering the stack has the same precedence as the top operator, then we remove the top operator and append it to the end of the postfix expression.
6. Repeat the application of rules 4 and 5 above, until the top operator has lower precedence than the operator entering the stack (or the stack is empty). At this point the new operator can be pushed onto the stack.
7. If you come to the end of the infix expression and there are operators still on the stack, pop them off, one by one (appending them to the end of the postfix expression), until the stack is empty.
8. Strings can contain “white space” characters (spaces and tabs), so be careful in parsing them.
The following suggestions are made with regard to the implementation of your program:
1. Use a stack from the STL class library to implement the conversion stack.