#include #include #include #include "date.h" using namespace std; const int date_length[] = { 0, //dummy element so that January will have subscript 1 31, //January 28, //February 31, //March 30, //April 31, //May 30, //June 31, //July 31, //August 30, //September 31, //October 30, //November 31 //December }; date::date(int initial_month, int initial_day, int initial_year) { if (initial_month < january || initial_month > december) { cerr << "bad month " << initial_month << "/" << initial_day << "/" << initial_year << "\n"; exit(EXIT_FAILURE); } if (initial_day < 1 || initial_day > date_length[initial_month]) { cerr << "bad day " << initial_month << "/" << initial_day << "/" << initial_year << "\n"; exit(EXIT_FAILURE); } year = initial_year; month = initial_month; day = initial_day; } date::date(int initial_day) { div_t divide = div(initial_day, 365); if (divide.rem < 0) { divide.rem += 365; --divide.quot; } year = divide.quot; day = divide.rem; month = 1; while (day > date_length[month]) { day -= date_length[month]; if (++month > 12) { month = 1; ++year; } } } date::date() { const time_t t = time(0); const tm *const p = localtime(&t); year = p->tm_year + 1900; month = p->tm_mon + 1; day = p->tm_mday; } void date::next(int count) { day += count; while (day < 1) { if (--month < 1) { month = 12; --year; } day += date_length[month]; } while (day > date_length[month]) { day -= date_length[month]; if (++month > 12) { month = 1; ++year; } } } int date::julian() const { int j = day; for (int m = 1; m < month; ++m) { j += date_length[m]; } return j; } ostream& operator<<(ostream& ost, const date &d) { return ost << d.month << "/" << d.day << "/" << d.year; } istream& operator>>(istream& ist, date& d) { int month; //uninitialized variable ist >> month; if (!ist) { //if (ist.operator!()) { return ist; } char c; //uninitialized variable ist >> c; if (!ist) { return ist; } if (c != '/') { ist.setstate(ios_base::failbit); return ist; } int day; //uninitialized variable ist >> day; if (!ist) { return ist; } ist >> c; if (!ist) { return ist; } if (c != '/') { ist.clear(ios_base::failbit); return ist; } int year; //uninitialized variable ist >> year; if (!ist) { return ist; } //Put no values into d until we've verified that all three are valid. if (month < date::january || month > date::december) { cerr << "bad month " << month << "\n"; ist.setstate(ios_base::failbit); return ist; } if (day < 1 || day > date_length[month]) { cerr << "bad day " << day << " of month " << month << "\n"; ist.setstate(ios_base::failbit); return ist; } d.year = year; d.month = month; d.day = day; return ist; }