44. Monthly calendar

Solving this task is actually partially based on the previous tasks. In order to print the days of the month as indicated in the problem, you should know:

  • What weekday is the first day of the month. This can be determined using the week_day() function created for a previous problem.
  • The number of days in the month. This can be determined using the date::year_month_day_last structure and retrieving the value of day().

With this information determined first, you should:

  • Print empty values for the first week before the first weekday
  • Print the day number with the proper formatting from 1 to the last day of the month
  • Break on a new line after every seven days (counting from day 1 of the first week, even though that could belong to the previous month)

The implementation of all this is shown here:

unsigned int week_day(int const y, unsigned int const m, 
unsigned int const d)
{
using namespace date;

if(m < 1 || m > 12 || d < 1 || d > 31) return 0;

auto const dt = date::year_month_day{year{ y }, month{ m }, day{ d }};
auto const tiso = iso_week::year_weeknum_weekday{ dt };

return (unsigned int)tiso.weekday();
}

void print_month_calendar(int const y, unsigned int m)
{
using namespace date;
std::cout << "Mon Tue Wed Thu Fri Sat Sun" << std::endl;

auto first_day_weekday = week_day(y, m, 1);
auto last_day = (unsigned int)year_month_day_last(
year{ y }, month_day_last{ month{ m } }).day();

unsigned int index = 1;
for (unsigned int day = 1; day < first_day_weekday; ++day, ++index)
{
std::cout << " ";
}

for (unsigned int day = 1; day <= last_day; ++day)
{
std::cout << std::right << std::setfill(' ') << std::setw(3)
<< day << ' ';
if (index++ % 7 == 0) std::cout << std::endl;
}

std::cout << std::endl;
}

int main()
{
print_month_calendar(2017, 12);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset