C++ Calendar problems

apache picture apache · Nov 10, 2013 · Viewed 7.5k times · Source

I'm trying to write a program that outputs a calendar. The user has to input the day in which the month starts (Monday-0, Tuesday-1, etc.), and how many days are in the month. Depending on what day the month starts, the calendar dates will start under that specific day. The issues I'm having is, I'm not sure how to get the calendar to start under a specific day, and I'm not sure how to get the dates to go to a new line after the 7 days. Any help would be appreciated. We haven't learnt much so far, so I'm really only allowed to use the basics, no functions or things like that.

Here's what I've got so far. I could be far out.

#include <iostream>
#include <iomanip>
#include <conio.h>

using namespace std;

int main()
{
    int monthStartDay, daysInMonth;

    cout << "Enter the first day of the month: ";
    cin >> monthStartDay;
    cout << "Enter how many days are in the month: ";
    cin >> daysInMonth;

    cout<<"\nSun   Mon   Tue   Wed   Thu   Fri   Sat";
    cout<<"\n\n"<<setw(2);

    for (int x=1; x <= daysInMonth; x++){
        cout << x << setw(6);

        for (int i=1; i == 6; i++) {
            cout << "\n";
        }
}
    return 0;
}

Answer

ktalik picture ktalik · Nov 10, 2013

The solution is using a new index, that will show a position in your calendar row. That is:

int startDayPostion = (monthStartDay + 1) % 7;

becouse you are counting zero from Monday, but your print is starting from Sunday. Hence a "shift to the right" is need. Add above line after reading a monthStartDay.

You need then to add a loop, which will print all spaces you need, and will shift above mentioned position to the desired startDayPostion:

int p = 0;
for (; p < startDayPostion; ++p) {
    cout << "" << setw(6);
}

(Insert this before your for loop with x)

Now, when you have a shift, you can simply fill the rest of the cells, keeping in mind that you are before the end (Sat).

After

cout << x << setw(6);

keep shifting the help index:

++p;

and then, if you are done with the line, go to the new line and reset p:

if (p > 6) {
    cout << '\n';
    p = 0;
}

I dont know why do you put here a for (int i=1; i == 6; i++) loop... You can simply delete those lines of code.