// Postfix Evaluator in C++
#include <stack>
#include <iostream>
#include <string>
using namespace std;
int evaluate_postfix_from_cin( )
{
stack<int> s;
cout<<"Enter a valid postfix expression\n";
string expression;
cin>>expression;
for (char ch: expression)
{
if (ch >= '0' && ch <= '9') {
s.push(ch - '0');
}
else {
int first_operand = s.top(); //First Operand
s.pop();
int second_operand = s.top(); //Second Operand
s.pop();
if (ch == '+') {
s.push(second_operand + first_operand);
}
else if (ch == '-') {
s.push(second_operand - first_operand);
}
else if (ch == '*') {
s.push(second_operand * first_operand);
}
else if (ch == '/') {
s.push(second_operand / first_operand);
}
}
}
return s.top();
}
int main()
{
cout << evaluate_postfix_from_cin();
return 0;
}
Comments
Leave a comment