You could create a struct
to keep the day, month and year:
struct date_t {
int day;
int month;
int year;
};
You could also add member functions to that struct
to simplify the input process:
struct date_t {
// ... the above member variables goes here ...
void enter_day(const char* prompt) {
std::cout << prompt << " day: ";
std::cin >> day;
}
void enter_month(const char* prompt) {
std::cout << prompt << " month: ";
std::cin >> month;
}
void enter_year(const char* prompt) {
std::cout << prompt << " year: ";
std::cin >> year;
}
void enter_all(const char* prompt) {
enter_day(prompt);
enter_month(prompt);
enter_year(prompt);
}
};
If you now create an array of date_t
:
date_t dates[2];
you can just call the enter_all()
function for both:
dates[0].enter_all("first");
dates[1].enter_all("second");
Now, everything related to the first date will be in dates[0]
, like dates[0].day
and everything related to the second date will be in dates[1]
, like dates[1].year
etc.
To compare two date_t
's you can add comparison operators. Here are a few examples. You should be able to use these to create the missing operators, like operator<=
etc. If you use C++20, you could implement operator<=>
.
// compare two `date_t`s to see if they are equal:
bool operator==(const date_t& lhs, const date_t& rhs) {
return lhs.day == rhs.day &&
lhs.month == rhs.month &&
lhs.year == rhs.year;
}
// check if the left date is before the right date
bool operator<(const date_t& lhs, const date_t& rhs) {
if(lhs.year != rhs.year) return lhs.year < rhs.year;
if(lhs.month != rhs.month) return lhs.month < rhs.month;
return lhs.day < rhs.day;
}
// check if the left date is after the right date
bool operator>(const date_t& lhs, const date_t& rhs) {
return rhs < lhs; // use the above operator<
}
With that you could do:
if(dates[0] == dates[1]) std::cout << "they are equal\n";
// or...
if(dates[0] < dates[1]) std::cout << "first < second\n";
// or...
if(dates[0] > dates[1]) std::cout << "first > second\n";