Design a class called Date that has integer data members to store month, day, an
ID: 3808622 • Letter: D
Question
Design a class called Date that has integer data members to store month, day, and year. The class should have a three-parameter (day-of-month, month, year) default constructor that allows the date to be set at the time a new Date object is created. If the user creates a Date object without passing any arguments , or if any of the values passed are invalid, the default values of 1, 1, 2001 (i.e., January 1, 2001) should be used (see below for the definition of invalid values ). The class should have member functions to print the date in the following formats:
3/15/13 (printNumerical)
March 15, 2013 (printMonthFirst)
15 March 2013 (printDateFirst)
For the purposes of this exercise, the following are invalid values :
For day of month: any value less than 1 or greater than 31 (so February 30 or April 31 would be acceptable)
For month: any value less than 1 or greater than 12
For year: any value less than 0
Explanation / Answer
Code:
#include<iostream>
#include<sstream>
using namespace std;
char months[12][10]={"January", "February", "March","April","May","June","July","August","September","October","November","December"};
class Date{
int dd,mm,yy;
public :
Date(){
dd=1;mm=1;yy=2001;
}
Date(int m,int d,int y){
dd=d;mm=m;yy=y;
bool check= checkdate(); //returns whether the give date is valid or not
if(!check){
cout<<"Invalid date give. Resetting to default"<<endl;
dd=mm=1; yy=2001;
}
}
bool checkdate(){
if(dd<1 || dd>31)
return false;
if(mm<1||mm>12)
return false;
if(yy<0)
return false;
return true;
}
void printNumerical()
{
cout<<mm<<"/"<<dd<<"/"<<(yy%100)<<endl;
}
void printMonthFirst()
{
cout<<months[mm-1]<<" "<<dd<<", "<<yy<<endl;
}
void printDateFirst()
{
cout<<dd<<" "<<months[mm-1]<<" "<<yy<<endl;
}
};
int main(void)
{
int m,d,y;
cout<<"Enter first date in mm-dd-yyyy format:"<<endl;
cin>>m>>d>>y;
Date d1(m,d,y);
d1.printNumerical();
d1.printMonthFirst();
d1.printDateFirst();
return 0;
}
Output:
Enter first date in mm-dd-yyyy format:
3 15 2013
3/15/13
March 15, 2013
15 March 2013
$ ./a.out
Enter first date in mm-dd-yyyy format:
3 32 2013
Invalid date give. Resetting to default
1/1/1
January 1, 2001
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.