Code:
class Date
{
public:
void setDate();
void printDate();
private:
int month;
int day;
int year;
int checkDay( int ) const;
};
void Date::setDate()
{
int mn,yr,dy;
cout<<"Enter Month:";
cin>>mn;
if ( mn > 0 && mn <= 12 ) // validate the month
month = mn;
else
{ // invalid month set to 1
month = 1;
cout << "Month " << mn << " invalid. Set to month 1.\n";
}
cout<<"Enter Year:";
cin>>yr;
if ( yr> 1970 && yr<=2009 )
year = yr;
else
{
year= 1990;
cout<< "Year "<< yr << " invalid. Set to year 1990.\n";
}
cout<<"Enter Day:";
cin>>dy; // should validate yr
day = checkDay( dy ); // validate the day
cout << endl;
}
void Date::printDate()
{
switch(month)
{
case 1:
cout<<"January ";
break;
case 2:
cout<<"February ";
break;
case 3:
cout<<"March ";
break;
case 4:
cout<<"April ";
break;
case 5:
cout<<"May ";
break;
case 6:
cout<<"June ";
break;
case 7:
cout<<"July ";
break;
case 8:
cout<<"August ";
break;
case 9:
cout<<"September ";
break;
case 10:
cout<<"October ";
break;
case 11:
cout<<"November ";
break;
case 12:
cout<<"December ";
break;
}//end switch
cout << day <<", "<< year << endl;
}
int Date::checkDay( int testDay ) const
{
static const int daysPerMonth[ 13 ] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;
if ( month == 2 && testDay == 29 && ( year % 400 == 0
|| ( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
cout << "Day " << testDay << " invalid. Set to day 1.\n";
return 1; // leave object in consistent state if bad value
} // end function checkDay
Here is the code for date,