-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression_evaluator_stack.cpp
More file actions
70 lines (57 loc) · 1.77 KB
/
Copy pathexpression_evaluator_stack.cpp
File metadata and controls
70 lines (57 loc) · 1.77 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
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
stack<char> operators;
stack<int> operands;
void evaluate(char* expression);
int main() {
cout << "Enter expression: " << endl;
char* expression = new char[255];
cin.getline(expression, 255);
while(strcmp(expression, "quit") != 0){
evaluate(expression);
cout << "Enter expression: " << endl;
cin.getline(expression, 255);
}
return 0;
}
void evaluate(char* expression){
for(int i = 0; i < strlen(expression); i++){
char c = expression[i];
if(c == '+' || c == '-' || c == '*'){
operators.push(c);
} else if(c >= '0' && c <= '9'){
int value = (int)c - (int)'0';
while(expression[i + 1] >= '0' && expression[i + 1] <= '9'){
value = value * 10 + ((int)expression[i+1] - (int)'0');
i++;
}
operands.push(value);
} else if(c == ')'){
char op = operators.top();
operators.pop();
if(op == '+'){
int val1 = operands.top();
operands.pop();
int val2 = operands.top();
operands.pop();
operands.push(val1 + val2);
} else if(op == '-'){
int val1 = operands.top();
operands.pop();
int val2 = operands.top();
operands.pop();
operands.push(val2 - val1);
} else {
int val1 = operands.top();
operands.pop();
int val2 = operands.top();
operands.pop();
operands.push(val1 * val2);
}
}
}
cout << operands.top() << endl;
operands.pop();
}