Write a Date class that validates day/month/year (including leap years), and a member function that returns the next day; test month and year boundaries.
Solution
main.cpp
#include <format>
#include <iostream>
#include <stdexcept>
#include <string>
class Date {
int d_, m_, y_;
static bool leap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }
static int days_in(int m, int y) {
static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return m == 2 && leap(y) ? 29 : days[m - 1];
}
public:
Date(int d, int m, int y) : d_(d), m_(m), y_(y) {
if (m < 1 || m > 12 || d < 1 || d > days_in(m, y)) throw std::invalid_argument("invalid date");
}
Date next() const {
int d = d_ + 1, m = m_, y = y_;
if (d > days_in(m, y)) { d = 1; if (++m > 12) { m = 1; ++y; } }
return {d, m, y};
}
std::string str() const { return std::format("{:02}-{:02}-{}", d_, m_, y_); }
};
int main() {
for (Date dt : {Date(28, 2, 2024), Date(28, 2, 2026), Date(31, 12, 2026), Date(30, 4, 2026)})
std::cout << dt.str() << " -> " << dt.next().str() << '\n';
try { Date bad(29, 2, 2026); } catch (const std::exception& e) { std::cout << e.what() << '\n'; }
return 0;
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!