inlinevoideval() { int b = nums.top(); nums.pop(); // the top of stk should be the secondary number int a = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); int res; if (op == '+') res = a + b; elseif (op == '-') res = a - b; elseif (op == '*') res = a * b; else res = a / b; nums.push(res); }
intmain() { cin.tie(nullptr)->sync_with_stdio(false); string s; cin >> s; int n = s.size(); for (int i = 0; i < n; i++) { char c = s[i]; if (isdigit(c)) { int j = i; int x = 0; for (; j < n && isdigit(s[j]); j++) { x = x * 10 + (s[j] - '0'); } i = j - 1; // because i++ later nums.push(x); } elseif (c == '(') { ops.push(c); } elseif (c == ')') { for (; ops.top() != '('; eval()); ops.pop(); } else { // determine the priority // compare the operator between the last operator on the stk and current operator for (; ops.size() && ops.top() != '(' && pr[ops.top()] >= pr[c]; eval()); ops.push(c); } } // the last entity could be a digital, since needs to do eval process once again // if the operation stack contains several operations and the previous ops has a lower priority than the later's, we have to loop eval that for (; ops.size(); eval()); //for (; nums.size(); nums.pop()) cout << nums.top() << endl; cout << nums.top() << endl; return0; }