https://rentry.org/PPP2_p365

// Code derived from Stroustrup's PPP2 book
// § 10.9 User-defined input operators
//  -and beginning on p 365

#include <iostream>

using namespace std;

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

class Date {
 public:
  enum Month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };

  Date() {}  // default constructor
  Date(int yy, Month mm, int dd) : y{yy}, m{mm}, d{dd} {}  // parm'd constructor

  int   year() const { return y; }
  Month month() const { return m; }
  int   day() const { return d; }

 private:
  int   y;
  Month m;
  int   d;
};

istream& operator>>(istream& is, Date& dd)
{
  int  y, m, d;
  char ch1, ch2, ch3, ch4;
  is >> ch1 >> y >> ch2 >> m >> ch3 >> d >> ch4;

  if (! is)
    return is;

  if (ch1 != '(' || ch2 != ',' || ch3 != ',' || ch4 != ')') {  // format error
    is.clear(ios_base::failbit);
    return is;
  }

  dd = Date{y, Date::Month(m), d};  // update dd
  return is;
}

ostream& operator<<(ostream& os, const Date& d)
{
  return os << '(' << d.year()   //
            << ',' << d.month()  //
            << ',' << d.day()    //
            << ')';
}

int main()
{
  cout << "Please enter input date (eg, (1994,3,29) ):  ";
  Date d;
  cin >> d;
  cout << '\n' << "date input was " << d << '\n';
}

build & run:

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

PrevUpNext

Edit
Pub: 07 Apr 2023 22:31 UTC
Edit: 03 May 2023 10:08 UTC
Views: 370