1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| #include <iostream> #include <stack> #include <memory> #include <string>
using namespace std;
class Caculater { private: string s;
int ans;
stack<int> nums; stack<char> ops;
int priority(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; return 0; }
void removeSpace() { string tmp; for (char ch : s) { if (ch != ' ') tmp += ch; } s = tmp; }
void compute() { if (nums.size() < 2 || ops.empty()) return; int y = nums.top(); nums.pop(); int x = nums.top(); nums.pop(); char op = ops.top(); ops.pop(); int ret = 0; if (op == '+') ret = x + y; else if (op == '-') ret = x - y; else if (op == '*') ret = x * y; else if (op == '/') ret = x / y; nums.push(ret); }
void process() { nums.push(0);
int n = s.size(); for (int i = 0; i < n; ++i) { char ch = s[i]; if (ch == '(') { ops.push(ch); } else if (ch == ')') { while (!ops.empty() && ops.top() != '(') compute(); ops.pop(); } else if (isdigit(ch)) { int j = i; int number = 0; while (j < n && isdigit(s[j])) { number = 10 * number + (s[j] - '0'); ++j; } nums.push(number); i = j - 1; } else { if (i > 0 && s[i - 1] == '(') { nums.push(0); } while (!ops.empty() && ops.top() != '(') { char op = ops.top(); if (priority(op) >= priority(ch)) { compute(); } else { break; } } ops.push(ch); } } while (!ops.empty() && ops.top() != '(') compute(); ans = nums.top(); while (!nums.empty()) nums.pop(); }
public: bool input() { cout << "please typeing correct caculate str here...\n"; if (getline(cin, s)) return true; return false; }
void output() { cout << "caculate result is: " << ans << endl; }
void run() { while (input()) { removeSpace(); process(); output(); } } };
int main() { auto ptr = make_unique<Caculater>(); ptr->run(); return 0; }
|