-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_postfix_expression.cpp
More file actions
37 lines (32 loc) · 877 Bytes
/
03_postfix_expression.cpp
File metadata and controls
37 lines (32 loc) · 877 Bytes
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
#include <iostream>
#include <stack>
#include <cstdlib>
#include <string>
int applyOperator(int a, int b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case 'x': return a * b;
case '/': return a / b;
}
return 0;
}
int main(int argc, char* argv[]) {
std::stack<int> st;
for (int i = 1; i < argc; i++) {
std::string token = argv[i];
// اگر عدد باشد
if (isdigit(token[0]) || (token[0] == '-' && token.size() > 1)) {
st.push(std::atoi(token.c_str()));
}
// اگر عملگر باشد
else {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
int result = applyOperator(a, b, token[0]);
st.push(result);
}
}
std::cout << st.top() << std::endl;
return 0;
}