67 lines
1.1 KiB
C++
67 lines
1.1 KiB
C++
#include "RPN.hpp"
|
|
|
|
RPN::RPN(){}
|
|
|
|
RPN::RPN(const RPN &other)
|
|
{
|
|
this->_stack = other._stack;
|
|
}
|
|
|
|
RPN &RPN::operator=(const RPN &other)
|
|
{
|
|
this->_stack = other._stack;
|
|
return (*this);
|
|
}
|
|
|
|
RPN::~RPN(){}
|
|
|
|
int RPN::compute(const std::string &string)
|
|
{
|
|
std::istringstream iss(string);
|
|
std::string token;
|
|
std::string ops = "+-*/";
|
|
int b;
|
|
int a;
|
|
while (iss >> token)
|
|
{
|
|
if (token.size() == 1)
|
|
{
|
|
if (isdigit(token[0]))
|
|
_stack.push(token[0] - '0');
|
|
else if (ops.find(token[0]) != std::string::npos)
|
|
{
|
|
if (_stack.size() <= 1)
|
|
throw std::runtime_error("Error");
|
|
b = _stack.top();
|
|
_stack.pop();
|
|
a = _stack.top();
|
|
_stack.pop();
|
|
switch (token[0])
|
|
{
|
|
case '+':
|
|
_stack.push(a + b);
|
|
break;
|
|
case '-':
|
|
_stack.push(a - b);
|
|
break;
|
|
case '*':
|
|
_stack.push(a * b);
|
|
break;
|
|
case '/':
|
|
if (b == 0)
|
|
throw std::runtime_error("Error");
|
|
_stack.push(a / b);
|
|
break;
|
|
}
|
|
}
|
|
else
|
|
throw std::runtime_error("Error");
|
|
}
|
|
else
|
|
throw std::runtime_error("Error");
|
|
}
|
|
if (_stack.size() != 1)
|
|
throw std::runtime_error("Error");
|
|
return _stack.top();
|
|
}
|