#ifndef CALCULATOR_HPP
#define CALCULATOR_HPP #include <string> #include <istream> #include <sstream> #include "stack.hpp" class Calculator { public: double calculate(const std::string& expr) { // PRE: expr in RPN (reversed polish notation) syntax std::istringstream in(expr); std::string token; double result; while (in >> token) { if (token == "+" || token == "-" || token == "*" || token == "/") { double op2{opstack.pop()}; double op1{opstack.pop()}; double result; if (token == "+") { result = op1 + op2; } else if (token == "-") { result = op1 - op2; } else if (token == "*") { result = op1 * op2; } else { result = op1 / op2; } opstack.push(result); } else { std::istringstream vin{token}; double value; if (vin >> value) { opstack.push(value); } else { std::cerr << "syntax error" << std::endl; } } } result = opstack.pop(); if (!opstack.empty()) { std::cerr << "bad expression" << std::endl; } return result; } private: Stack opstack; }; #endif // CALCULATOR_HPP |