-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRPN.cpp
More file actions
79 lines (70 loc) · 1.73 KB
/
Copy pathRPN.cpp
File metadata and controls
79 lines (70 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "RPN.hpp"
#include "Defines.hpp"
#include <cstdlib>
#include <sstream>
#include <stdexcept>
bool
RPN::isOperator (std::string str)
{
if (str == "+" || str == "-" || str == "*" || str == "/")
return true;
return false;
}
void
RPN::executeOperator (std::stack<int> &stk, int first, std::string token,
int second)
{
if (token == "+")
stk.push (second + first);
else if (token == "-")
stk.push (second - first);
else if (token == "*")
stk.push (second * first);
else if (token == "/")
{
if (first == 0)
throw std::invalid_argument ("Division by zero");
stk.push (second / first);
}
}
RPN::RPN (std::string expression)
{
std::stack<int> stk;
int first, second;
std::string token;
std::istringstream iss (expression);
while (iss >> token)
{
if (isOperator (token))
{
if (stk.size () < 2)
throw std::invalid_argument ("Not enough numbers for operation");
first = stk.top ();
stk.pop ();
second = stk.top ();
stk.pop ();
executeOperator (stk, first, token, second);
}
else if (std::isdigit (token[0]))
{
int number = std::atoi (token.c_str ());
if (number < 0 || number > 9)
throw std::invalid_argument ("Numbers must be between 0 and 9");
stk.push (number);
}
else
throw std::invalid_argument ("Invalid character in expression");
}
if (stk.size () != 1)
throw std::invalid_argument ("Numbers were left in the stack");
print (stk.top ());
}
RPN::RPN () {}
RPN::RPN (const RPN &other) { (void)other; }
RPN &
RPN::operator= (const RPN &other)
{
(void)other;
return *this;
}
RPN::~RPN () {}