So I was asked to write a code which would take in 2 dates of the format mm/dd/yyyy, validate that they were good dates (including leap years), then output the dates in chronological order. It works as intended for every date I throw at it but it seems way to complicated with all the nested if statement. Any suggestions on how to streamline it? Please keep in mind I'm a beginner and have only just learned to use arrays (pointers next week). Please give an example if you have a suggestion. "Use an array!" doesn't help so much. lol Thanks for your time.
/*
Program assignment name: 2_Dates
Author:Christopher D*****
*/
#include <stdio.h>
int main (void)
{
int mm=0, dd=0, yyyy=0, mm2=0, dd2=0, yyyy2=0;
int first_date = 0, second_date = 0;
while(1)
{
printf("Enter first date (mm/dd/yyyy): ");
scanf("%d /%d /%d", &mm, &dd, &yyyy);
printf("\n");
printf("Enter second date (mm/dd/yyyy): ");
scanf("%d /%d /%d", &mm2, &dd2, &yyyy2);
printf("\n");
/* Checks to see if months are between 1-12, day 1-31, & years 0-9999 */
if(yyyy>=1 && yyyy<=9999 && yyyy2>=1 && yyyy2<=9999 &&
mm>=1 && mm<=12 && mm2>=1 && mm2<=12 && dd>=1 && dd<=31 &&
dd2>=1 && dd2<=31)
{
/* Checks months that don't have 31 days */
if(mm==2 && dd>28 && dd<30 || mm2==2 && dd2>28 && dd2<30)
{
/* Leap year test for February*/
if(((yyyy % 4 !=0 && yyyy % 100 ==0) || yyyy % 400 !=0) ||
((yyyy2 % 4 !=0 && yyyy2 % 100 ==0) || yyyy2 % 400 !=0))
{
printf("February doesn't have that many days. ");
printf("Please try again.\n\n");
continue; /* Passes control to the end of the while loop */
}
}
if(mm==4 && dd>30 || mm2==4 && dd>30)
{
printf("April doesn't have that many days. ");
printf("Please try again.\n\n");
continue;
}
if(mm==6 && dd>30 || mm2==6 && dd>30)
{
printf("June doesn't have that many days. ");
printf("Please try again.\n\n");
continue;
}
if(mm==9 && dd>30 || mm2==9 && dd>30)
{
printf("September doesn't have that many days. ");
printf("Please try again.\n\n");
continue;
}
if(mm==11 && dd>30 || mm2==11 && dd>30)
{
printf("November doesn't have that many days. ");
printf("Please try again.\n\n");
continue;
}
break; /* breaks from loop if input was a valid date */
}
printf("You have entered an invalid date. ");
printf("Please try again.\n\n");
while (getchar() != '\n'); /* Clears input buffer */
}
/* Converts dates into integer values */
first_date = (yyyy * 10000) + (mm * 100) + dd;
second_date = (yyyy2 * 10000) + (mm2 * 100) + dd2;
/* Compares these values and prints the earlier date first */
if (first_date < second_date)
{
printf("%2d/%2d/%4d is earlier than %2d/%2d/%4d\n",
mm, dd, yyyy, mm2, dd2, yyyy2);
}
else if (first_date > second_date)
{
printf("%2d/%2d/%4d is earlier than %2d/%2d/%4d\n",
mm2, dd2, yyyy2, mm, dd, yyyy);
}
else if (first_date == second_date)
{
printf("The dates you entered are the same\n");
}
return 0;
}