This is in C++: Please write a program that prompts the user to enter a person’s
ID: 3672734 • Letter: T
Question
This is in C++:
Please write a program that prompts the user to enter a person’s date of birth in
numeric form such as 8-27-1980. The program then outputs the date of
birth in the form: August 27, 1980. Your program must contain at least two
exception classes: invalidDay and invalidMonth. If the user enters
an invalid value for day, then the program should throw and catch an
invalidDay object. Similar conventions for the invalid values of month
and year. (Note that your program must handle a leap year.)
Explanation / Answer
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class invalidday
{
public:
invalidday()
{
message = "Invalid day";
}
invalidday(int day)
{
message = day;
}
string what()
{
return message;
}
private:
string message;
};
class invalidmonth
{
public:
invalidmonth()
{
message = "Invalid month";
}
invalidmonth(int month)
{
message = month;
}
string what()
{
return message;
}
private:
string message;
};
int main()
{
try {
int day,month, year;
cout<<"Please input date of birth mm-dd-yy: ";
string str;
cin >>str;
int n = str.size();
int i;
int x=0, flag=0;
str[n] = '-';
for(i=0;i<=n;i++)
{
if(str[i] != '-') x= x*10 + (str[i]-'0');
else if(str[i] == '-' && flag == 0) { month = x; x=0; flag =1;}
else if(str[i] == '-' && flag == 1) { day= x; x=0; flag =2;}
else if(str[i] == '-' && flag == 2) { year = x; x=0;}
}
if(month <=0 || month >12) throw invalidmonth();
else if(month == 2 && day == 29 && year%4 != 0) throw invalidday(); // checking leap year
else if(month == 2 && day == 30 ) throw invalidday();
else if(month == 2 && day == 31 ) throw invalidday();
else if(day <=0||day>31 ) throw invalidday();
string monthstring;
switch(month){
case 1: monthstring = "January";
break;
case 2: monthstring = "February";
break;
case 3: monthstring = "March";
break;
case 4: monthstring = "April";
break;
case 5: monthstring = "May";
break;
case 6: monthstring = "June";
break;
case 7: monthstring = "July";
break;
case 8: monthstring = "August";
break;
case 9: monthstring = "September";
break;
case 10: monthstring = "October";
break;
case 11: monthstring = "November";
break;
case 12: monthstring = "December";
break;
default: monthstring = "Invalid Month";
break;
}
cout<<monthstring<<" "<<day<<", "<<year;
}
catch(invalidday x) // catch ivalid day
{
cout<<x.what()<<endl;;
}
catch(invalidmonth y) // catch invalid month
{
cout<<y.what()<<endl;;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.