#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() throw() {
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 ,"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 ,"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 ,"Day is out of range!!!");
}
else
{
if (day < 0 || day > DAYSINMONTH[month - 1]) throw DateException(year , month ,day ,"Day is out of range!!!");
}
}
friend ostream& operator<<(ostream& stream, const Date& obj){
stream <<"----------------------------------\n"<<endl;
stream <<obj.day<<"/"<<obj.month<<"/"<<obj.year<<endl;
stream <<"----------------------------------\n"<<endl;
return stream;
}
};
int main () {
// just for test our classes
Date date[5];
for (int i = 0 ;i < 5; i++)
{
try{
date[i].Input();
}
catch(DateException dateExp)
{
cout<<dateExp.what()<<endl;
cout<<"Information about date : "<<endl;
cout<<dateExp.GetDay()<<"/"<<dateExp.GetMonth()<<"/"<<dateExp.GetYear()<<endl;
--i;
}
}
cout<<endl<<"Display date : "<<endl;
for (int i = 0; i < 5; i++)
{
cout<<date[i];
}
system("pause");
return 0;
}
Comments
Leave a comment