Files
cpp09/ex01/RPN.cpp
2026-04-24 13:22:16 +02:00

108 lines
2.8 KiB
C++

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* RPN.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aortigos <aortigos@student.42malaga.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/04/24 12:37:09 by aortigos #+# #+# */
/* Updated: 2026/04/24 12:37:09 by aortigos ### ########.fr */
/* */
/* ************************************************************************** */
#include "RPN.hpp"
//////////////////
// Constructors //
//////////////////
RPN::RPN()
{
// std::cout << "RPN default constructor called" << std::endl;
}
RPN::RPN(const RPN &other)
{
*this = other;
// std::cout << "RPN copy constructor called" << std::endl;
}
RPN& RPN::operator=(const RPN &other)
{
if (this != &other)
{
this->numbers = other.numbers;
}
// std::cout << "RPN copy assignment operator called" << std::endl;
return (*this);
}
RPN::~RPN()
{
// std::cout << "RPN destructor called" << std::endl;
}
void RPN::math(std::string data)
{
std::istringstream ss(data);
std::string token;
int nbr;
while (ss >> token)
{
if (isToken(token))
{
if (numbers.size() < 2)
{
std::cout << "Error." << std::endl;
return ;
}
int b = numbers.top();
numbers.pop();
int a = numbers.top();
numbers.pop();
if (token == "+")
numbers.push(a + b);
if (token == "-")
numbers.push(a - b);
if (token == "*")
numbers.push(a * b);
if (token == "/")
numbers.push(a / b);
}
else
{
char *endptr;
nbr = std::strtol(token.c_str(), &endptr, 10);
if (*endptr != '\0')
{
std::cout << "Error." << std::endl;
return ;
}
if (nbr >= 10)
{
std::cout << "Error." << std::endl;
return ;
}
this->numbers.push(nbr);
}
}
if (numbers.size() != 1)
{
std::cout << "Error." << std::endl;
return ;
}
std::cout << numbers.top() << std::endl;
}
bool RPN::isToken(std::string token)
{
return (token == "+" || token == "-"
|| token == "*" || token == "/");
}