Files
cpp09/ex01/RPN.cpp
2025-08-27 15:58:23 +02:00

56 lines
1.2 KiB
C++

#include "RPN.hpp"
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("division by 0 is not possible");
return first / second;
}
typedef int (*OperatorFunctions)(int, int);
void rpn(char *av)
{
OperatorFunctions calc[128] = { NULL };
calc['+'] = &add;
calc['-'] = &subst;
calc['*'] = &mult;
calc['/'] = ÷
std::istringstream ss_input((std::string(av)));
std::stack<int> stack;
std::string value;
while (ss_input >> value)
{
if (value.size() != 1)
throw std::invalid_argument("invalid value");
if (isdigit(value[0]))
{
stack.push(value[0] - '0');
continue ;
}
if (!calc[(int) value[0]])
throw std::invalid_argument("invalid character");
if (stack.size() < 2)
throw std::range_error("not enough operands");
int a = stack.top(); stack.pop();
int b = stack.top(); stack.pop();
stack.push(calc[(int) value[0]](b, a));
}
if (stack.size() != 1)
throw std::range_error("there are too many operands");
std::cout << stack.top() << std::endl;
}