Untitled

 avatar
unknown
c_cpp
2 years ago
2.1 kB
10
Indexable
#include <iostream>
#include <stack>
#include <string>
#include <queue>
#include <iomanip>
using namespace std;

string topostfix(string myString);
void steps_postfix(string myString);
int precedence(char op);

int main(){	
	
	cout << "Postfix" << endl;
	cout << "Expression \t\t Operator \t\t Operand" << endl;
	
	//cout << topostfix("x((a+b)*(c+d))");
	cout << topostfix("a+b*c+d");
	//cout << topostfix("a*b*c+d*e*f+g");

	return 0;
}

string topostfix(string myString){
	char myChar[myString.length()];
	strcpy(myChar, myString.c_str());
	
	stack<char> s_op;
	stack<char> temp;
	
	string result = "";
	
	for(int i = 0; i < myString.length(); i++){
		
		if(myChar[i] != '*' && myChar[i] != '+' && myChar[i] != '-' && myChar[i] != '/' && myChar[i] != '(' && myChar[i] != ')'){	//	if operand
			result += myChar[i];
			
			cout << myChar[i]; // for step-by-step output

//			// output!!!!
//			if(s_op.empty()){
//				cout << setw(21) << " " << setw(18) << result << endl;
//			}
//			else{
//				while(!s_op.empty()){
//					cout << setw(21) << s_op.top() << setw(18) << result << endl;
//					temp.push(s_op.top());
//					s_op.pop();
//				}
//				while(!temp.empty()){
//					s_op.push(temp.top());
//					temp.pop();
//				}
//			}
//
		}
		else if (myChar[i] == '(') {
				s_op.push(myChar[i]);
		}
		else if(myChar[i] == ')'){
				while(s_op.top() != '('){
					result += s_op.top();
					s_op.pop();
				}
			s_op.pop();	// pop the opening parenthesis
		}
			
		else{	// if char is an operator
			while(!s_op.empty() && precedence(s_op.top()) >= precedence(myChar[i])){
				result += s_op.top();
				s_op.pop();
			}
			cout << myChar[i];	// step-by-step output

			s_op.push(myChar[i]);

			//temp.push((s_op.top()));
			

			
		}
		
		
		// print on all lines area
	

		//cout << setw(18) << "hi" << endl;
		cout << setw(39) << result << endl;
	}
	
	while(!s_op.empty()){
		result += s_op.top();
		s_op.pop();
	}
	
	cout << setw(33) << "Output: " ;
	return result;
}

int precedence (char op){
	if(op == '*') return 4;
	else if (op == '/') return 3;
	else if(op == '+') return 2;
	else if(op == '-') return 1;
	return 0;
}


Editor is loading...