1
0
This repository has been archived on 2025-07-15. You can view files and clone it, but cannot push or open issues or pull requests.
Files
CPP_Module_09/ex01/RPN.cpp

74 lines
2.3 KiB
C++

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* RPN.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adjoly <adjoly@student.42angouleme.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/06/03 12:07:59 by adjoly #+# #+# */
/* Updated: 2025/07/03 20:15:20 by adjoly ### ########.fr */
/* */
/* ************************************************************************** */
#include <RPN.hpp>
#include <cctype>
#include <exception>
#include <sstream>
#include <stack>
#include <stdexcept>
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<int> &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<int> &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<int> 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;
}