📄 calc.cpp
字号:
#include <stack>
#include <iostream>
#include <stdexcept>
using namespace std;
/**
A class that implements a simple RPN calculator.
*/
class Calculator
{
public:
enum BinaryOperator {PLUS, MINUS, TIMES, DIVIDE};
/**
Return the current top of stack, or throw
exception if there is no current value.
@return current top of stack
*/
int current_memory() const;
/**
Push integer value onto top of stack.
@param value integer to be placed on stack
*/
void push_operand(int value);
/**
Perform indicated binary operation.
@param op operation to be performed
*/
void do_operator(BinaryOperator op);
private:
stack<int> data;
};
/**
A class that represents an input error.
*/
class CalcInputException : public runtime_error
{
public:
CalcInputException(string why) : runtime_error(why) {}
};
int Calculator::current_memory() const
{
if (data.empty())
throw CalcInputException("Stack Underflow");
return data.top();
}
inline void Calculator::push_operand(int value)
{
data.push(value);
}
void Calculator::do_operator(BinaryOperator op)
{
int right = current_memory();
data.pop();
int left = current_memory();
data.pop();
if (op == PLUS) data.push(left + right);
else if (op == MINUS) data.push(left - right);
else if (op == TIMES) data.push(left * right);
else if (op == DIVIDE) data.push(left / right);
}
/**
Read from input stream, performing operations.
Input consists of numbers, binary operators, or commands.
command p - print
command q - quit
@param in input stream to be read
*/
void read(istream& in)
{
Calculator calc;
char c;
while (in >> c)
if (isdigit(c))
{
int intval;
in.putback(c);
in >> intval;
calc.push_operand(intval);
}
else if (c == '+')
calc.do_operator(Calculator::PLUS);
else if (c == '-')
calc.do_operator(Calculator::MINUS);
else if (c == '*')
calc.do_operator(Calculator::TIMES);
else if (c == '/')
calc.do_operator(Calculator::DIVIDE);
else if (c == 'p')
cout << calc.current_memory() << "\n";
else if (c == 'q')
return;
}
int main()
{
try
{
read(cin);
}
catch (exception& e)
{
cout << "caught exception " << e.what() << "\n";
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -