A previous article has already talked about how to convert infix expressions into postfix expressions:
https://blog.csdn.net/weixin_39138071/article/details/79809533
Now we implement how to evaluate based on postfix expression in C++
1. Traverse the suffix expression;
2. If the scanned number is a number, push it onto the stack and continue to traverse;
3. If the scanned item is a binary operator + - * /, the top of the stack is two elements Pop the stack in turn, and then store the result into the stack after calculation; (the C++ implementation only considers the binary operator)
4. If the scanned item is a unary operator, pop the top element of the stack and execute the operation, and then push the result onto the stack;
5. After traversing the suffix expression, you will find that there is actually only one element left in the stack, which is the result, and you can print it directly.
C++ code:
#include<iostream>
#include<stack>
#include<string>
using namespacestd;
int main(){
string s;
getline ( cin , s);
stack<int> sta;
int left=0;
int right=0;
for(int i=0;i<s.size();i++){
if(s[i]>='0'&&s[i]<='9'){
string s2="";
while(s[i]>='0'&&s[i]<='9'){
s2+=s[i];
i++;
}
what. push ( stand (s2));
}
else if(s[i]!=' '){
if(!sta.empty()){
right=sta.top();
stand. pop ();
}
if(!sta.empty()){
left=sta.top();
stand. pop ();
}
switch(s[i]){
case '+':
sta.push(left+right);
break;
case '-':
sta.push(left-right);
break;
case '*':
sta.push(left*right);
break;
case '/':
sta.push(left/right);
break;
default:
break;
}
}
}
cout<<sta.top()<<endl;
return0;
}
operation result:
9 3 1 - 3 * + 10 2 / +
20
Program ended with exit code: 0