Newer
Older
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
#include <iostream>
#include <optional>
#include <stack>
#include <stdexcept>
#include <climits>
#include <unordered_map>
#include <iterator>
std::stack<int> stack;
int plus(int a, int b) {
return a + b;
}
int minus(int a, int b) {
return b - a;
}
int produkt(int a, int b) {
return a * b;
}
int division(int a, int b) {
if (b == 0) {
throw std::invalid_argument("Division durch 0!");
}
return a / b;
}
std::unordered_map<char, decltype(&plus)> map {
{'+', plus},
{'-', minus},
{'*', produkt},
{'/', division}
};
int evaluate(const std::string &s) {
int a,b;
std::unordered_map<char, decltype(&plus)>::iterator iter;
for (char c : s) {
if (std::isdigit(c)) {
stack.push(c - '0');
} else {
if (stack.size() >= 2 ) {
iter = map.find(c);
if (iter != map.end()) {
a = stack.top();
stack.pop();
b = stack.top();
stack.pop();
stack.push(iter->second(b, a));
} else {
throw std::invalid_argument("Ungueltige Sonderzeichen");
}
} else {
throw std::invalid_argument("Ungueltige Anzahl an Zahlen");
}
}
}
if (stack.size() > 1 || stack.size() == 0) {
throw std::invalid_argument("Ungueltige Eingabe");
}
return stack.top();
}
int main() {
std::string user_input;
std::cin >> user_input;
if (user_input.empty()) { std::cout << "Empty input\n"; return 1; }
std::cout << "User input is \"" << user_input << "\"\n";
int result = INT_MAX;
try {
result = evaluate(user_input);
} catch (const std::exception &e) {
std::cout << e.what();
}
if (result != INT_MAX) {
std::cout << "Result is: " << result << '\n';
}
}