/***************************************************** Author : Yan Huang Date : 02.27.07 Synopsis: convert a infix expression to a postfix expression Note: Some codes have been purposely taken out. and the precedence is not set properly. **************************************************************/ #include #include using namespace std; /************************************************ Get the next token, symbol is the character representation, which is returned, the token is represented by its enumerated value, which is returned in the function name ***************************************************/ enum tokenEnum{lparen,rparen,plus,minus,divide,times,mod,eos,operand}; int precedence[]= {1,2,3,4,5,1,1,3,4,1,1}; char tokenSymbol[]= {'(',')','+','-','/','*','%','\n'}; tokenEnum get_token() { char symbol; symbol = cin.get(); /* get rid of the space */ while (symbol == ' '){ symbol = cin.get(); } switch (symbol) { case '(' : return lparen; case ')' : return rparen; case '+': return plus; case '-' : return minus; case '/' : return divide; case '*' : return times; case '%' : return mod; case 'E' : return eos; default : cin.unget(); return operand; /* no error checking, default is operand */ } } void main() { /* output the postfix of the expression. The expression string, the stack, and top are global */ char symbol; tokenEnum token; int op; stack myStack; for (token = get_token(); token != eos; token = get_token()) { if (token is operand){ cin >> op; cout << op; } else if (token == lparen) { myStack.push(token); } else if (token == rparen ){ /*unstack tokens until left parenthesis */ ... } myStack.pop(); } else{ /* remove and print symbols whose precedence is greater than or equal to the current token's precedence and the stack is not empty and before we see left parenthesis*/ while(!myStack.empty() && precedence[myStack.top()] >= precedence[token] && myStack.top() !=lparen){ ... } myStack.push(token); } } while (!myStack.empty()){ cout << tokenSymbol[myStack.top()]; myStack.pop(); } cout << endl; }