-
Notifications
You must be signed in to change notification settings - Fork 2
/
postFixEvaluation.cpp
61 lines (53 loc) · 1.31 KB
/
postFixEvaluation.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
#include<bits/stdc++.h>
using namespace std;
double calculate(double a, double b, char ch) {
switch(ch) {
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
case '^':
return pow(a, b);
}
}
double postfixEvaluate(string postfix) {
stack<double>stk;
int i;
for(i = 0; i < postfix[i]; i++) {
char ch = postfix[i];
if(ch == ',' || ch == ' ') continue;
else if(ch >= '0' && ch <= '9') {
string str = "";
while(postfix[i] != ',' && postfix[i]) {
str += postfix[i];
i++;
}
double num = stod(str);
stk.push(num);
}
else if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch < 'Z') {
double value;
cout << "Enter the value of " << ch << " : ";
cin >> value;
stk.push(value);
}
else {
double b = stk.top();
stk.pop();
double a = stk.top();
stk.pop();
stk.push(calculate(a, b, ch));
}
}
return stk.top();
}
int main() {
string p = "a,2,^";
double x = postfixEvaluate(p);
cout << x << endl;
return 0;
}