-
Notifications
You must be signed in to change notification settings - Fork 4
/
calculator_v0.cpp
46 lines (44 loc) · 1.37 KB
/
calculator_v0.cpp
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
#include <iostream>
#include <stdexcept>
using namespace std;
// 简单计算器v0,支持+,-,*,/运算
// bug:*,/和+,-的优先级相同
int main() {
try {
cout << "Please enter expression (we can handle +, -, * and /)\n";
cout << "add ; to end expression (e.g., 1+2*3;):";
int lval = 0, rval;
char op;
cin >> lval; // read leftmost operand
if (!cin)
throw invalid_argument("no first operand");
while (cin >> op) { // read operator and right-hand operand repeatedly
if (op != ';')
cin >> rval;
if (!cin)
throw invalid_argument("no second operand");
switch (op) {
case '+':
lval += rval;
break;
case '-':
lval -= rval;
break;
case '*':
lval *= rval;
break;
case '/':
lval /= rval;
break;
default: // not another operator: print result
cout << "Result: " << lval << '\n';
return 0;
}
}
throw invalid_argument("bad expression");
}
catch (invalid_argument& e) {
cerr << "error: " << e.what() << '\n';
return 0;
}
}