CS 250infixpostfix code -...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: file:///C|/infixpostfix%20code.txt //this program converts an infix expression into its equivalent postfix #include<iostream> #include<string> #include<stack> using namespace std; //stack priority function //input: operator character //output: return stack priority value for the input operator int stackpriority(char op) { switch (op) { case '*': case'/': return 2; case '+': case '-': return 1; case '(': case '#': return 0; default: cerr<<"Invalid operator, Program is terminated...\n"; exit(1); } } //infix priority function //input: operator character //output: return infix priority value for the input operator int infixPriority(char op) { switch (op) { case '(': return 3; case '*': case'/': return 2; case '+': file:///C|/infixpostfix%20code.txt (1 of 3) [11/25/2007 9:09:26 PM] file:///C|/infixpostfix%20code.txt case '-': return 1; case ')': case '#': return 0; default: cerr<<"Invalid operator, Program is terminated...\n"; exit(1); } } //infix to postfix conversion function //input: an infix expression entered using the standard input //output: infix is converted to its equivalent postfix void InfixToPostfix( string &postfix ) { char item , ch; stack< char > opstack; opstack.push('#'); cout<<"Please inter your infix Expression and terminate it with #:\n"; do { cin.get(ch); if ( ( 'A' <= ch ) && ( ch <= 'Z' ) ) //transfer ch to postfix postfix = postfix + ch; else if ( ch == ')' )//pop stack until encounter matching left parenthesis { item=opstack.top(); opstack.pop(); while ( item != '(' ) { postfix = postfix + item; item=opstack.top(); opstack.pop(); } } else if ( ch == '#' )//pop rest of stack to postfix { while ( ! opstack.empty() ) { file:///C|/infixpostfix%20code.txt (2 of 3) [11/25/2007 9:09:26 PM] file:///C|/infixpostfix%20code.txt item=opstack.top(); opstack.pop(); postfix = postfix + item; } } else //pop stack until encounter item of lower priority then push incoming character { item=opstack.top(); opstack.pop(); while ( stackpriority( item ) >= infixPriority(ch) ) { postfix = postfix + item; item=opstack.top(); opstack.pop(); } opstack.push( item ); opstack.push( ch ); } } while ( ch != '#' ); } //main function void main() { string postfix;//used by infix to postfix converter to store result InfixToPostfix(postfix); cout<<postfix<<endl; } file:///C|/infixpostfix%20code.txt (3 of 3) [11/25/2007 9:09:26 PM] ...
View Full Document

This note was uploaded on 03/15/2010 for the course STATISTIC 472 taught by Professor Amjad during the Spring '08 term at Yarmouk University.

Ask a homework question - tutors are online