Code:
//header file - cannot be modified
#ifndef _DATE_H_
#define _DATE_H_
/////////////////////////////////////////////////////////////
// DATE1.H - DATE CLASS DECLARATION //
/////////////////////////////////////////////////////////////
#include <iostream.h>
#include <iomanip.h>
#include <string.h>
#include <assert.h>
int leapYear(int year); //returns: 1 (leap year), 0 (not leap year)
enum {MM = 1}; //default month
enum {DD = 1}; //default day
enum {YY = 1}; //default year
enum {MAX_YY = 99999}; //maximum year
enum {MAX_LINE = 1024}; //maximum size of input line
#define NA "" //default name
const int days [] [13] =
{
{0,31,28,31,30,31,30,31,31,30,31,30,31}, //non-leap year
{0,31,29,31,30,31,30,31,31,30,31,30,31} //leap year
}
const char *months[] =
{"Invalid", "January", "February", "March" ,
"April", "May", "June", "July", "August",
"September", "October", "November", "December"
};
class Date
{
public:
Date(int m = MM, int d = DD, int y = YY, const char *name = NA);
void setDate(int m, int d, int y, const char *name = NA);
~Date(); //destructor
void print() const; //display data
private:
int theMonth;
int theDay;
int theYear;
char *theName;
char date_name[MAX_LINE];
void setString(const char *str); //utility function
};
#endif
// implementation
#include "date.h"
Date::Date(int m, int d, int y, const char *name)
{
setDate(m, d, y, name);
}
Date::~Date()
{
delete [] theName;
}
void Date::setDate(int m, int d, int y, const char *name)
{
theMonth = (m >= 1 && m <= 12) ? m : MM;
theDay = (d >= 1 && d <= 31) ? d : DD;
theYear = (y >= 0 && y <= MAX_YY) ? y : YY;
setString(theName);
}
void Date::print() const
{
if (theDay > days[leapYear(theYear)] [theMonth])
theDay = DD;
cout << endl << "You entered date" << endl;
if ('\0' != date_name[0])
cout << date_name << ": ";
cout << months[theMonth] << ' ' << theDay << ", " <<
theYear << endl;
}
void Date::setString(const char *str)
{
theName = new char[strlen(str) + 1];
assert(theName != 0);
strcpy(theName, str);
}
int leapYear(int year)
{
if (year % 4 == 0 && year % 100 || year % 400 == 0)
return 1;
else
return 0;
}
// main test driver
//date1tst.cpp - test driver to test Date class
#include "date.h"
int main()
{
Date d1;
d1.print();
Date d2(12,27,1992, "d2(12,27,1992)");
d2.print();
cout << endl;
Date d3(0,99,10000, "d3(0,99,10000)");
d3.print();
cout << endl;
d1.setDate(2,28,1992, "d1.setDate(2,28,1992)");
d1.print();
cout << endl;
Date d4(2,29,2000, "d4(2.29,2000)");
d4.print();
cout << endl;
Date d5(2,29, 2001, "d5(2,29,2001)");
d5.print();
cout << endl;
return 0;
}
The output should be this
January 1, 1
d2(12,27,1992): December 27, 1992
d3(0,99,10000): January 1, 1
d1.setdate(2,28,1992): February 28, 1992
d4(2,29,2000): February 29, 2000
d5(2, 29, 2001): February 1, 2001