-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
122 lines (115 loc) · 2.06 KB
/
main.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <string>
#include <stack>
#include <exception>
using namespace std;
string infixToPostfix(string &infix)
{
stack<char> yolo;
string ans("");
yolo.push('(');
infix += ')';
for (int i = 0; !yolo.empty(); i++)
{
if (infix[i] == '(')
yolo.push('(');
else if (infix[i] == ')')
{
while (yolo.top() != '(')
{
ans += yolo.top();
yolo.pop();
}
yolo.pop();
}
else if (infix[i] >= '0' && infix[i] <= '9')
{
ans += '|';
while (infix[i] == '.' || (infix[i] >= '0' && infix[i] <= '9') || infix[i] == '_')
{
if (infix[i] != '_')
ans += infix[i];
i++;
}
i--;
ans += '|';
}
else if (infix[i] == '*' || infix[i] == '/' || infix[i] == '%')
{
while (yolo.top() == '*' || yolo.top() == '/' || yolo.top() == '%')
{
ans += yolo.top();
yolo.pop();
}
yolo.push(infix[i]);
}
else if (infix[i] == '+' || infix[i] == '-')
{
while (yolo.top() == '*' || yolo.top() == '/' || yolo.top() == '%' || yolo.top() == '+' || yolo.top() == '-')
{
ans += yolo.top();
yolo.pop();
}
yolo.push(infix[i]);
}
else if (infix[i] != ' ')
{
throw new exception;
}
}
infix.pop_back();
return ans;
}
double calculate(string postfix)
{
stack<double> regis;
for (int i = 0; i < postfix.length(); i++)
{
if (postfix[i] == '|')
{
i++;
string tmp;
while (postfix[i] != '|')
tmp += postfix[i++];
regis.push(stod(tmp));
}
else
{
double b = regis.top();
regis.pop();
switch (postfix[i])
{
case '+':
regis.top() += b;
break;
case '-':
regis.top() -= b;
break;
case '*':
regis.top() *= b;
break;
case '/':
regis.top() /= b;
break;
case '%':
regis.top() = (int)regis.top() % (int)b;
break;
}
}
}
return regis.top();
}
int main()
{
string exp;
while (true)
{
printf("Enter your expression (-1 to exit)\n");
getline(cin, exp);
if (exp == "-1")
break;
string post = infixToPostfix(exp);
cout << post << endl;
cout << calculate(post) << endl;
}
}