/
postfix.cpp
142 lines (138 loc) · 2.58 KB
/
postfix.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include<iostream>
#include<string>
#include<iomanip>
#include<stack>
using namespace std;
void postfix(char *);
bool separation(stack<double> &, char, bool);
void cal(stack<double> &, char);
int main()
{
while (true)
{
cout << "Input to Infix : ";
char input[1005] = { 0, };
cin >> input;
cout << input << endl;
if (!strcmp(input, "exit")) break;
cout << "Change to Postfix : ";
postfix(input);
cout << endl;
}
return 0;
}
bool separation(stack<double> &num, char ch, bool last)
{
static char temp[1005] = { 0, };
static int cnt = 0;
static bool real = false;
if (ch >= '0' && ch <= '9')
{
temp[cnt++] = ch;
real = true;
if (last)
{
int res = atoi(temp);
cout << res << ' ';
num.push(res);
real = false;
cnt = 0;
memset(temp, 0, sizeof(temp));
}
return false;
}
else
{
cnt = 0;
int res = atoi(temp);
if (real)
{
cout << res << ' ';
num.push(res);
real = false;
}
memset(temp, 0, sizeof(temp));
}
return false;
}
void cal(stack<double> &num, char symbol)
{
double temp = 0;
temp += num.top();
num.pop();
switch (symbol)
{
case '+': temp = num.top() + temp; break;
case '-': temp = num.top() - temp; break;
case '*': temp = num.top() * temp; break;
case '/': temp = num.top() / temp; break;
}
num.pop();
num.push(temp);
}
void postfix(char *input)
{
stack<char> post;
stack<double> num;
bool nth, last = false;
for (int i = 0; i < strlen(input); i++)
{
if (strlen(input) - 1 == i) last = true;
if (input[i] == ' ') continue;
else if (separation(num, input[i], last)) continue;
if (post.empty()) nth = true;
else nth = false;
if (input[i] == '(') post.push(input[i]);
else if (input[i] == ')')
{
while (true)
{
if (post.top() == '(')
{
post.pop();
break;
}
cal(num, post.top());
cout << post.top() << ' ';
post.pop();
}
}
else if (input[i] == '+' || input[i] == '-')
{
if (!nth)
{
while (post.top() != '(')
{
cal(num, post.top());
cout << post.top() << ' ';
post.pop();
if (post.empty()) break;
}
}
post.push(input[i]);
}
else if (input[i] == '*' || input[i] == '/')
{
if (!nth)
{
while (post.top() != '(' && post.top() != '+' && post.top() != '-')
{
cal(num, post.top());
cout << post.top() << ' ';
post.pop();
}
}
post.push(input[i]);
}
}
while (!post.empty())
{
cal(num, post.top());
cout << post.top() << ' ';
post.pop();
}
cout << endl;
cout << "----------------------------------" << endl;
cout.precision(2);
cout << "Result : " << fixed << num.top() << endl;
}