-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.hpp
105 lines (97 loc) · 2.66 KB
/
calculator.hpp
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
#ifndef TO_ASSIGN_CALCULATOR_H_
#define TO_ASSIGN_CALCULATOR_H_
namespace calculator {
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0;
}
}
string infixToPostfix(string infix) {
stack<char> opStack;
stringstream postfix;
for (char c : infix) {
if (isdigit(c)) {
postfix << c;
} else if (c == '(') {
opStack.push(c);
} else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix << opStack.top();
opStack.pop();
}
opStack.pop();
} else {
while (!opStack.empty() && precedence(opStack.top()) >= precedence(c)) {
postfix << opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
while (!opStack.empty()) {
postfix << opStack.top();
opStack.pop();
}
return postfix.str();
}
int evaluatePostfix(string postfix) {
stack<int> operands;
for (char c : postfix) {
if (isdigit(c)) {
operands.push(c - '0');
} else {
if (operands.size() < 2) {
throw runtime_error("Syntax error");
}
int operand2 = operands.top();
operands.pop();
int operand1 = operands.top();
operands.pop();
switch (c) {
case '+':
operands.push(operand1 + operand2);
break;
case '-':
operands.push(operand1 - operand2);
break;
case '*':
operands.push(operand1 * operand2);
break;
case '/':
if (operand2 == 0) {
throw runtime_error("Divide by zero");
}
operands.push(operand1 / operand2);
break;
default:
throw runtime_error("Invalid character");
}
}
}
if (operands.size() != 1) {
throw runtime_error("Syntax error");
}
return operands.top();
}
void main(){
cout<<"Input 0 to exit:\n";
while(1){
string infix = "0";
cin>>infix;
if(infix=="0")return;
if (cin.fail()) {
cout << "Invalid input" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
string postfix = infixToPostfix(infix);
int result = evaluatePostfix(postfix);
cout << "= " << result << endl;
}
}
}
#endif