-3

I'm working on a program in c++ that will get ask the user to enter a date such as (12 31) and the program will output the number of days and the day of the week so (12 31) will return (365 Tue). So far I have

 #include <iostream>
 using namespace std;
 int main (){ 
 while (true)  
 cout << "Enter date: "; cin >> mon >>day;
 if (!mon && !day) break; //this is so that 
 when the user enters (0 0) the program ends
 }
 cout << "Bye" << endl;
 return 0;
 }

How should I get the program to match the date to a number and day of the week? I'm just starting to learn c++ through online tutorials so I'm not that fluent but I do know some stuff. Do I need to create a new function? My main issue is that I've hit a roadblock on how I should get the program to count the days from the given date, (I was thinking a range from 1-365). Not looking for an answer but some help would be nice.

1 Answers1

1

Not looking for an answer but some help would be nice.

when you do cin >> mon >>day first declare the int variables mon and day but also check the return, so if (!(cin >> mon day)) ...EOF occurred...

If you look at the function managing time you have the ones declared through <time.h> including mktime and as you can see they work with struct tm containing exactly what you want :

int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */

mktime is also exactly what you need :

The mktime() function converts a broken-down time structure, expressed as local time, to calendar time representation.

So you just have to set the fields :

int tm_sec;    /* Seconds (0-60) */
int tm_min;    /* Minutes (0-59) */
int tm_hour;   /* Hours (0-23) */
int tm_mday;   /* Day of the month (1-31) */
int tm_mon;    /* Month (0-11) */
int tm_year;   /* Year - 1900 */

tm_sec/tm_min/tm_hour can be 0, tm_mday and tm_month are the inputs you have to get (just decrement tm_month after)

The only missing part is the current year, but it is easy to set it, use time_t time(time_t *tloc); returning the current time then convert it to a struct tm using struct tm *localtime(const time_t *timep);, then set the others fields as describe above, then call mktime

Now you can do your program

bruno
  • 32,421
  • 7
  • 25
  • 37