Newer
Older
#include <iostream>
#include <optional>
#include <stack>
#include <stdexcept>
#include <climits>
#include <unordered_map>
#include <iterator>

Benjamin Basmaci
committed
/*
* Adds two integers
*/
}

Benjamin Basmaci
committed
/*
* Subtracts integer b from integer a
*/
}

Benjamin Basmaci
committed
/*
* Multiplies two integers
*/
}

Benjamin Basmaci
committed
/*
* Divides integer b from integer a, throwing an exception when b is zero.
* Throws an std::invalid_argument exceptions if invalid parameters are provided.

Benjamin Basmaci
committed
*/
if (b == 0) {
throw std::invalid_argument("Tried to divide by 0.");
}
return a / b;
using binary_operator = decltype(&add);
std::stack<int> stack;
std::unordered_map<char, binary_operator> map {
{'+', add},
{'-', subtract},
{'*', multiply},
{'/', divide}
};
decltype(map)::iterator iter;
for (char c : s) {
if (std::isdigit(c)) {
stack.push(c - '0');
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() {
std::string user_input;
std::cin >> user_input;
if (user_input.empty()) {
std::cout << "Empty input\n";
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();
}