-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program6.cpp
50 lines (50 loc) · 1.12 KB
/
Program6.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
// Evaluation of postfix expression
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;
// only for single digit number
int evalPostfix(string &s)
{
stack<int> st;
for (int i = 0; i < s.length(); i++)
{
if (isdigit(s[i]))
{
st.push(s[i] - '0');
}
else
{
int operand1 = st.top();
st.pop();
int operand2 = st.top();
st.pop();
switch (s[i])
{
case '+':
st.push(operand1 + operand2);
break;
case '-':
st.push(operand2 - operand1);
break;
case '*':
st.push(operand1 * operand2);
break;
case '/':
st.push(operand2 / operand1);
break;
case '^':
st.push(pow(operand2, operand1));
}
}
}
return st.top();
}
int main()
{
string p_expr;
cout << "Enter the Postfix Expression: ";
getline(cin, p_expr);
cout << evalPostfix(p_expr) << endl;
return 0;
}