SO i got this program date_struct.c going and it looks like everything works except the printout part.
When input 2 dates to get the numbers of days between them nothing happens, the program ends. This also happens when i try inputting a date and an integer, and returns a new date which is the given date, plus the given number of days, again the program ends without printing out the answers.
Can anyone see any errors in my code?
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
struct mydate {
int day;
int month;
int year;
};
int daysbetween
(struct mydate *d1, struct mydate *d2)
{
struct tm timeptr1 = {0}, timeptr2 = {0};
time_t date1, date2;
long long diff_t = 0;
timeptr1.tm_mday = d1->day;
timeptr1.tm_mon = d1->month - 1;
timeptr1.tm_year = d1->year - 1900;
date1 = mktime(&timeptr1);
timeptr2.tm_mday = d2->day;
timeptr2.tm_mon = d2->month - 1;
timeptr2.tm_year = d2->year - 1900;
date2 = mktime(&timeptr2);
diff_t = (date2 - date1) / (60 * 60 * 24);
return (diff_t);
}
char *adddays(struct mydate *d1, int days)
{
struct tm timeptr = {0}; time_t date1;
timeptr.tm_mday = d1->day;
timeptr.tm_mon = d1->month - 1;
timeptr.tm_year = d1->year - 1900;
date1 = mktime(&timeptr);
date1 = date1 + (days * 24 * 60 * 60);
return (ctime(&date1));
}
struct mydate *getdate() {
struct mydate *d = malloc(sizeof(struct mydate) * 1);
printf("Enter date (mm/dd/yyyy): ");
scanf("%d/%d/%d", &(d->month),&(d->day) , &(d->year));
return d;
}
main() {
int choice = 0;
struct mydate *d1, *d2;
char str_time[256] = "";
int days;
while ((choice > 3) || (choice < 1))
{
printf("Date_Struct.c Menu:\n");
printf("1. Difference Between two dates\n");
printf("2. Add days and give next date\n");
printf("3. Exit program\n");
printf("\n Enter a number:");
scanf("%d", &choice);
}
switch (choice)
{
case 1:
printf("Enter first date: \n");
d1 = getdate();
printf("Enter second date: \n");
d2 = getdate();
printf("Number of days in between is: %d\n", daysbetween(d1, d2));
break;
case 2:
printf("Enter a date: \n");
d1 = getdate();
printf("Enter number of days: ");
scanf("%d", &days);
strcpy(str_time, adddays(d1, days));
printf("Next date is:%s\n", str_time);
break;
case 3:
exit (0);
}
}