https://rentry.org/PPP2_calc_util_cpp

// 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);
}

main_calculator.cppCalculator.hCalculator.cppcalc_util.h

Edit
Pub: 09 Mar 2023 05:05 UTC
Edit: 03 May 2023 10:45 UTC
Views: 469