/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* RPN.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: adjoly +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2025/06/03 12:07:59 by adjoly #+# #+# */ /* Updated: 2025/07/03 20:15:20 by adjoly ### ########.fr */ /* */ /* ************************************************************************** */ #include #include #include #include #include #include int add(int first, int second) { return first + second; } int subst(int first, int second) { return first - second; } int mult(int first, int second) { return first * second; } int div(int first, int second) { if (second == 0) throw std::invalid_argument("can't divide by 0 sorry D:"); return first / second; } void calc(int (*op)(int, int), std::stack &stack) { if (stack.size() < 2) throw std::range_error("not enough operands"); int second = stack.top(); stack.pop(); int first = stack.top(); stack.pop(); stack.push(op(first, second)); } void handle(std::string::const_iterator c, std::stack &stack) { if (*c == ' ') return; else if (std::isdigit(*c)) stack.push(*c - '0'); else if (*c == '+') calc(add, stack); else if (*c == '-') calc(subst, stack); else if (*c == '*') calc(mult, stack); else if (*c == '/') calc(div, stack); else throw std::invalid_argument("invalid caracter detected"); } void rpn(char *av) { std::string str(av); std::stack stack; for (auto it = range(str)) { try { handle(it, stack); } catch (std::exception &e) { std::stringstream str; str << "Error: " << e.what() << " : " << *it; throw std::runtime_error(str.str()); } } if (stack.size() != 1) throw std::runtime_error("Error: leftover operands in stack"); std::cout << stack.top() << std::endl; }