-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathshell.cpp
97 lines (84 loc) · 2.25 KB
/
shell.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
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
#include <iostream> // fixed, cout, endl, string
#include <sstream> // stringstream
#include <iomanip> // setprecision
using namespace std;
struct Calculator {
int batteryMax;
int battery;
float display;
Calculator(int batteryMax = 0) : batteryMax(batteryMax) {
this->battery = 0;
this->display = 0.0f;
}
void chargeBattery(int value) {
if(value < 0) {
return;
}
this->battery += value;
this->battery = std::min(this->battery, this->batteryMax);
}
void sum(int a, int b) {
if(this->battery == 0){
cout << "fail: bateria insuficiente" << endl;
return;
}
this->battery -= 1;
this->display = (a + b);
}
void division(int num, int den) {
if(this->battery == 0){
cout << "fail: bateria insuficiente" << endl;
return;
}
this->battery -= 1;
if(den == 0) {
cout << "fail: divisao por zero" << endl;
return;
}
this->display = (float) num / den;
}
std::string str() const {
stringstream ss;
ss << "display = " << fixed << setprecision(2) << this->display << ", battery = " << this->battery;
return ss.str();
}
};
int main() {
Calculator calc;
while (true) {
string line, cmd;
getline(cin, line);
cout << "$" << line << '\n';
stringstream par(line);
par >> cmd;
if (cmd == "end") {
break;
}
else if (cmd == "init") {
int batteryMax {};
par >> batteryMax;
calc = Calculator(batteryMax);
}
else if (cmd == "show") {
cout << calc.str() << '\n';
}
else if (cmd == "charge") {
int increment {};
par >> increment;
calc.chargeBattery(increment);
}
else if (cmd == "sum") {
int a {}, b {};
par >> a >> b;
calc.sum(a, b);
}
else if (cmd == "div") {
int num {}, den {};
par >> num >> den;
calc.division(num, den);
}
else {
cout << "fail: comando invalido" << endl;
}
}
}