I'm a writing a C++ program to Evaluate a PostFIx expression. This is the following code:
#include <iostream>
#include <string>
#include <stack>
#include <conio.h>
using namespace std;
int operand1;
int operand2;
bool operator_test(char character){ //to test whether its an operator or not
if(character=='+' || character=='-' || character=='*' || character=='/')
return true;
else
return false;
}
bool operand_test(char character){ //to test whether its an operand or not
if(!operator_test(character) && character!='(' && character!=')')
return true;
else
return false;
}
int DoOperation(char operation,int operand1,int operand2){
if(operation=='+') return operand1+operand2;
else if(operation=='-') return operand1-operand2;
else if(operation=='*') return operand1*operand2;
else if(operation=='/') return operand1/operand2;
}
int main(){
string expression;
cout<<"ENTER POSTFIX EXPRESSION"<<endl;
cin>>expression;
stack<int>test_stack;
int result;
for(int i=0;i<expression.length();i++){
if(operand_test(expression[i]))
test_stack.push(expression[i]);
else if(operator_test(expression[i]))
operand2=test_stack.top();
test_stack.pop();
operand1=test_stack.top();
test_stack.pop();
result=DoOperation(expression[i],operand1,operand2);
test_stack.push(result);
}
cout<<"EVALUATION: "<<test_stack.top()<<endl;
getch();
return 0;
}
If I enter 23+ it should give 5 as output. But it's giving 51. What am I doing wrong here?? thanks in advance