https://rentry.org/PPP2_p375

// Code derived from Stroustrup's PPP2 book
// § 10.11.3 Changing representations
//  -and beginning on p 375

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

void error(const string s) { throw runtime_error(s); }
void error(const string s1, const string s2) { error(s1 + s2); }

//------------------------------------------------------------------------------

vector<string> month_input_tbl = {"jan", "feb", "mar", "apr", "may", "jun",
                                  "jul", "aug", "sep", "oct", "nov", "dec"};

// is s the name of a month? If so return its index [0:11] otherwise –1
int month_to_int(string s)
{
  for (int i = 0; i < 12; ++i)
    if (month_input_tbl[i] == s)
      return i;

  return -1;
}

vector<string> month_print_tbl = {
    "January", "February", "March",     "April",   "May",      "June",
    "July",    "August",   "September", "October", "November", "December"};

// months [0:11]
string int_to_month(int i)
{
  if (i < 0 || 12 <= i)
    error("bad month index");

  return month_print_tbl[i];
}

int main()
try {
  string const jan_string{"jan"};
  string const feb_string{"feb"};
  string const dec_string{"dec"};

  cout << "jan's index: " << month_to_int(jan_string) << '\n';
  cout << "feb's index: " << month_to_int(feb_string) << '\n';
  cout << "dec's index: " << month_to_int(dec_string) << '\n';

  cout << "month index 0's print format: " << int_to_month(0) << '\n';
  cout << "month index 1's print format: " << int_to_month(1) << '\n';
  cout << "month index 11's print format: " << int_to_month(11) << '\n';

} catch (exception& e) {
  cerr << "error: " << e.what() << '\n';
  return 1;

} catch (...) {
  cerr << "Oops: unknown exception!\n";
  return 2;
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_10/main_p375.cpp && ./a.out

PrevUp

Edit
Pub: 07 Apr 2023 22:41 UTC
Edit: 03 May 2023 10:19 UTC
Views: 338