78 lines
2.4 KiB
C++
78 lines
2.4 KiB
C++
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* RPN.cpp :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: adjoly <adjoly@student.42angouleme.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2025/06/03 12:07:59 by adjoly #+# #+# */
|
|
/* Updated: 2025/06/03 15:56:22 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 calc(int, int), std::string::const_iterator ,
|
|
std::stack<int> &stack) {
|
|
int first, second;
|
|
|
|
if (stack.size() != 2)
|
|
throw std::range_error("need 2 at least two number");
|
|
second = stack.top();
|
|
stack.pop();
|
|
first = stack.top();
|
|
stack.pop();
|
|
if (stack.size() != 0)
|
|
throw std::range_error("too much number");
|
|
stack.push(calc(first, second));
|
|
// if (*(c + 1) != ' ' || *(c + 1) != '\0')
|
|
// throw std::invalid_argument("");
|
|
}
|
|
|
|
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, c, stack);
|
|
else if (*c == '-')
|
|
calc(subst, c, stack);
|
|
else if (*c == '*')
|
|
calc(mult, c, stack);
|
|
else if (*c == '/')
|
|
calc(div, c, 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());
|
|
}
|
|
}
|
|
std::cout << stack.top() << std::endl;
|
|
}
|