#pragma once
#include "stdafx.h"
#include "Stack.h"
class Calculator {
private:
Stack<double> s;
public:
Calculator(void) {}
virtual ~Calculator() {}
void Enter(double operand) {
s.Push(operand);
}
void GetTwoOperands(double &operand1, double &operand2) {
if (s.IsEmpty()) {
cerr << "No operand to be pop !" << endl;
s.Clear();
exit(1);
}
operand1 = s.Pop();
if (s.IsEmpty) {
cerr << "No operand to be pop !" << endl;
s.Clear();
exit(1);
}
operand2 = s.Pop();
}
void Compute(char op) {
double operand1, operand2, result;
GetTwoOperands(operand1, operand2);
switch (op) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/': if (operand2 == 0) {
cerr << "Divided by 0 !" << endl;
s.Clear();
exit(1);
} else
result = operand1 / operand2; break;
default:
break;
}
s.Push(result);
}
void Clear() {
s.Clear();
}
void Run() {
char op;
double operand;
cin >> op;
while (op != '=') {
switch (op) {
case'+':case'-':case'*':case'/':
Compute(op); break;
default:cin.putback(op);
cin >> operand;
Enter(operand); break;
}
cin >> op;
}
cout << s.Pop() << endl;
Clear();
}
};