Skip to content
Snippets Groups Projects
Commit 7502cd32 authored by Florian Steinkamp's avatar Florian Steinkamp
Browse files

Merge branch 'master' into 'master'

fix indentation

See merge request fs878995/rpn_calculator!4
parents 0302253c fb902685
No related branches found
No related tags found
No related merge requests found
......@@ -12,67 +12,67 @@ std::stack<int> stack;
* Adds two integers
*/
int add(int a, int b) {
return a + b;
return a + b;
}
/*
* Subtracts integer b from integer a
*/
int subtract(int a, int b) {
return b - a;
return b - a;
}
/*
* Multiplies two integers
*/
int multiply(int a, int b) {
return a * b;
return a * b;
}
/*
* Divides integer b from integer a, throwing an exception when b is zero
*/
int divide(int a, int b) {
if (b == 0) {
throw std::invalid_argument("Tried to divide by 0.");
}
return a / b;
if (b == 0) {
throw std::invalid_argument("Tried to divide by 0.");
}
return a / b;
}
std::unordered_map<char, decltype(&plus)> map {
{'+', add},
{'-', subtract},
{'*', multiply},
{'/', divide}
{'+', add},
{'-', subtract},
{'*', multiply},
{'/', divide}
};
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("Invalid character found.");
}
} else {
throw std::invalid_argument("Invalid number of digits.");
}
}
}
if (stack.size() > 1 || stack.size() == 0) {
throw std::invalid_argument("Invalid input.");
}
return stack.top();
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("Invalid character found.");
}
} else {
throw std::invalid_argument("Invalid number of digits.");
}
}
}
if (stack.size() > 1 || stack.size() == 0) {
throw std::invalid_argument("Invalid input.");
}
return stack.top();
}
int main() {
......@@ -86,15 +86,15 @@ int main() {
std::cout << "User input is \"" << user_input << "\"\n";
int result = INT_MAX;
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';
}
try {
result = evaluate(user_input);
} catch (const std::exception &e) {
std::cout << e.what();
}
if (result != INT_MAX) {
std::cout << "Result is: " << result << '\n';
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment