Postfix evaluation use stack in C++.
Problem: Postfix Evaluation Using Stack in C++
#include<iostream>
#include<stack>
using namespace std;
int methodPostFixEvaluation()
{
string userInput;
stack<char>Stack;
int Operand01,Operand02;
cout<<"Enter your postfix expression:"<<" ";
cin>>userInput;
for (int i = 0; i < userInput.length(); i++)
{
// if the current character is an operand, push it into the stack
if (userInput[i] >= '0' && userInput[i] <= '9')
{
Stack.push(userInput[i] - '0');
continue;
}
else{
Operand01= Stack.top();
Stack.pop();
Operand02= Stack.top();
Stack.pop();
if (userInput[i] == '+')
{
Stack.push(Operand02 + Operand01);
}
else if (userInput[i] == '-')
{
Stack.push(Operand02 - Operand01);
}
else if (userInput[i] == '*')
{
Stack.push(Operand02 * Operand01);
}
else if (userInput[i] == '/')
{
Stack.push(Operand02 / Operand01);
}
}
}
return Stack.top();
}
int main()
{
cout<<"YOur postfix evaluation is:"<<" "<<methodPostFixEvaluation()<<endl;
return 0;
}
No comments