https://rentry.org/PPP2_calc_util_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 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// Code derived from Stroustrup's PPP2 book // From Chs. 6 & 7, The Calculator Project - CLI edition // -and beginning on p 174 #include "calc_util.h" #include <stdexcept> #include <vector> using std::runtime_error; using std::vector; //------------------------------------------------------------------------------ vector<Variable> var_table; //------------------------------------------------------------------------------ Variable::Variable(std::string const& n, double const v, bool const va) : name{n}, value{v}, var{va} { } //------------------------------------------------------------------------------ double define_name(std::string const& s, double const val, bool const var) { if (is_declared(s)) error(s, " declared twice"); var_table.push_back(Variable{s, val, var}); return val; } //------------------------------------------------------------------------------ bool is_declared(std::string const& var) { for (unsigned i = 0; i < var_table.size(); ++i) if (var_table[i].name == var) return true; return false; } //------------------------------------------------------------------------------ double get_value(std::string const& s) { for (unsigned i = 0; i < var_table.size(); ++i) if (var_table[i].name == s) return var_table[i].value; error("get: undefined variable ", s); return 0.0; // shouldn't reach here } //------------------------------------------------------------------------------ void set_value(std::string const& s, double const d) { for (unsigned i = 0; i < var_table.size(); ++i) { if (var_table[i].name == s) { if (var_table[i].var == false) error(s, " is a constant"); var_table[i].value = d; return; } } error("set: undefined variable ", s); } //------------------------------------------------------------------------------ void error(std::string const& s1) { throw runtime_error(s1); } //------------------------------------------------------------------------------ void error(std::string const& s1, std::string const& s2) { throw runtime_error(s1 + s2); } sauce: Bjarne Stroustrup's PPP2 textbook /robowaifu/'s official C++ learning textbook thread main_calculator.cpp • Calculator.h • Calculator.cpp • calc_util.h