///////////////////////////postfix_evaluation
#include "stack_linked.cpp"
#include <sstream>
//#include<string> <string> is included in <sstream>
template<class T>
class PostfixEvaluation{
StackLinked<T> sl;
T calculate(T a, T b, char c){
/*
to calculate a and b using operator c,
because c is a character,
we need to use this function to convert the char to the relevant operator
*/
T tmp;
switch(c){
case '+': tmp = a+b; break;
case '-': tmp = a-b; break;
case '*': tmp = a*b; break;
case '/': tmp = a/b; break;
case '^': tmp = a^b; break;
}
return tmp;
}
bool isOperator(char c){
/* to check if the character is an operator */
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='^')
return true;
else
return false;
}
T StringToNumber ( string Text ){
/*
to convert string into number
the data extracted from p_xpr is string/char
*/
istringstream ss(Text);
T result;
return ss >> result ? result : 0;
}
public:
T evaluate(string p_xpr){
/*
to evaluate the value of given "string" postfix expression
*/
T tmp;
int i=0;
while(p_xpr[i]!='\0'){
if(isOperator(p_xpr[i]))
{
/*
pop two number from the stack and calculate
the result of these number using calculate(T,T,char) function
return the result to the stack
*/
T t1,t2;
t1 = sl.Top();
sl.pop();
t2 = sl.Top();
sl.pop();
tmp = calculate(t2 , t1 , p_xpr[i]);
sl.push(tmp);
i++;
}
else if(p_xpr[i] !=' '){
/*
if the current char is number, put this number
into "char t[]" array. convert this array into string by adding \0.
convert this string into number using StringToNumber(string).
put the number into stack
*/
char t[10];
int j=0;
while(p_xpr[i] !=' '){
if(isOperator(p_xpr[i])) break;
t[j++] = p_xpr[i++];
}
t[j++] ='\0';
sl.push( StringToNumber (t));
}else{
i++;
}
}
tmp = sl.Top();
sl.pop();
return tmp;
}
};
main(){
PostfixEvaluation<int> pe;
string p_xpr;
cout<<"\nEnter postfix expression :\n";
getline(cin,p_xpr);
cout<<"The result of postfix evaluation is: "<<pe.evaluate(p_xpr)<<endl;
}