1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream>
#include <iomanip>
#include <cstdlib>
bool isLeapYear(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
int daysInMonth(int year, int month) {
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if (month == 2)
return isLeapYear(year) ? 29 : 28;
return 31;
}
// Jan 1, 1753 was a monday (offset 1)
int computeOffset(int year, int month) {
int a = (year - 1753) / 4;
int b = (year - 1701) / 100;
int c = (year - 1601) / 400;
int leap_years = a - b + c;
int offset = (1 + year - 1753 + leap_years) % 7;
for (int m = 1; m < month; m++)
offset = (offset + daysInMonth(year, m)) % 7;
return offset;
}
void displayCalendar(int year, int month) {
const char *month_names[] = {
"January","February","March","April","May","June",
"July","August","September","October","November","December"};
int numberOfDays = daysInMonth(year, month);
int pos = computeOffset(year, month) + 1;
std::cout << month_names[month-1] << ", " << year << '\n';
std::cout << " Su Mo Tu We Th Fr Sa\n";
std::cout << std::setw(pos * 4) << 1;
for (int date = 2; date <= numberOfDays; ) {
if (pos++ % 7 == 0) std::cout << '\n';
std::cout << std::setw(4) << date++;
}
std::cout << '\n';
}
int main(int argc, char **argv) {
if (argc != 3) {
std::cerr << "Usage: mycal YEAR MONTH\n";
return 1;
}
int year = atoi(argv[1]), month = atoi(argv[2]);
if (year < 1753) {
std::cerr << "Error: YEAR must be greater than 1752\n";
return 1;
}
if (month < 1 || month > 12) {
std::cerr << "Error: MONTH must be from 1 to 12\n";
return 1;
}
displayCalendar(year, month);
}
|