1 #include<bits/stdc++.h> 2 using namespace std; 3 /** 4 * 仿LISP运算 5 * 模拟(sub (mul 2 4) (div 9 3)) 6 * @return 7 */ 8 9 int main() { 10 int mark = 0; 11 int num1,num2; 12 string str; 13 stack<int> numStatck; 14 stack<string> operStack; 15 16 getline(cin,str); 17 for(int i = 0; i < str.length() ; i++) 18 { 19 char c = str[i]; 20 cout<<c<<" "; 21 if(c == '(') { 22 operStack.push(str.substr(i+1,3)); 23 i += 4; 24 mark = i + 1; 25 } else if(c == ')') { 26 if(mark < i) { 27 //stoi string --> int 28 numStatck.push(stoi(str.substr(mark,i-mark))); 29 30 i++; 31 mark = i + 1; 32 } 33 num1 = numStatck.top(); 34 numStatck.pop(); 35 num2 = numStatck.top(); 36 numStatck.pop(); 37 string ex = operStack.top(); 38 operStack.pop (); 39 40 if (ex == " add " ) 41 numStatck.push (num1 + num2); 42 else if (f == " sub " ) 43 numStatck.push (num1- num2); 44 else if (f == " mul " ) 45 numStatck.push (* num1 num2); 46 else if (f == " div " ) 47 if (num2 ==0) cout <<"ERROR"<<endl; 48 else 49 numStatck.push(num2/num1); 50 51 } else { 52 if(c == ' ') { 53 if(mark < i ) { 54 numStatck.push(stoi(str.substr(mark,i-mark))); 55 mark = i + 1; 56 } 57 } 58 } 59 } 60 cout<<"结果:"; 61 cout<<numStatck.top()<<endl; 62 return 0; 63 }