-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicCalculatorTwo.cc
55 lines (50 loc) · 1.19 KB
/
BasicCalculatorTwo.cc
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
#include "bits/stdc++.h"
using namespace std;
int calculateh(istringstream& s);
int calculate(string str) {
istringstream s(str);
return calculateh(s);
}
int calculateh(istringstream& s) {
int result = 0;
bool adding = true;
char c;
while(s) {
c = s.peek();
if (!s) break;
switch(c) {
case '+':
c = s.get();
adding = true;
break;
case '-':
c = s.get();
adding = false;
break;
case '(':
c = s.get();
if (adding) result += calculateh(s);
else result -= calculateh(s);
break;
case ')':
c = s.get();
return result;
case ' ':
c = s.get();
break;
default:
int n = 0;
s >> n;
if (adding) result += n;
else result -= n;
char c;
c = s.get();
if (s) s.unget();
break;
}
}
return result;
}
int main() {
cout << calculate("2-1 + 2 ");
}