#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <string>
using namespace std;
//array that stores the number of days for each month of non-leap year
const int DAYSINMONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class DateException : public runtime_error{
private:
int year;
int month;
int day;
public:
explicit DateException (int _year, int _month, int _day, const string& msg="") : runtime_error(msg){
year = _year;
month = _month;
day = _day;
};
int GetYear() {return year;}
int GetMonth() {return month;}
int GetDay() {return day;}
};
class Date{
private:
int year;
int month;
int day;
public:
Date() {year = 0; month = 0; day = 0;}
void Input() {
bool leapOrNot = false;
// Year must be greater than 0 (To check for leap)
cout<<"Enter year : ";
cin>>year;
if (year < 1) throw DateException(year , month ,day ,"Error!!Year must be greater than 0!!!");
// check for leap
if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) leapOrNot = true;
else
leapOrNot = false;
cout<<"Enter month : ";
cin>>month;
if (month < 1 || month > 12 ) throw DateException(year , month ,day ,"Error!!Month is out of range!!!");
cout<<"Enter day : ";
cin>>day;
// if the year is a leap year and the month of February
if (month == 2 && leapOrNot) {
if (day < 0 || day > 29) throw DateException(year , month ,day ,"Error!!Day is out of range!!!");
}
else
{
if (day < 0 || day > DAYSINMONTH[month - 1]) throw DateException(year , month ,day ,"Error!!Day is out of range!!!");
}
}
void SetDateToDefault(void){
year = 2010;
month = 1;
day = 1;
}
friend ostream& operator<<(ostream& stream, const Date& obj){
stream <<"----------------------------------\n"<<endl;
stream <<obj.day<<"/"<<obj.month<<"/"<<obj.year<<endl<<endl;
stream <<"----------------------------------\n"<<endl;
return stream;
}
};
int main () {
Date date[5];
for (int i = 0 ;i < 5; i++)
{
try{
date[i].Input();
}
catch(exception& exp)
{
cout<<"Was caught exception!!"<<endl;
cout<<exp.what()<<endl;
cout<<"Date will be set by default"<<endl;
date[i].SetDateToDefault();
}
}
cout<<endl<<"Dates : "<<endl;
for (int i = 0; i < 5; i++)
{
cout<<date[i];
}
system("pause");
return 0;
}
Comments
Leave a comment