Reputation: 13
The following program is written in C IDE : Code::Blocks 16.01
Question : Write a program to find difference of two dates in years,months and dates. Dates are in valid range and first date falls before second.
//To find difference of two dates in years,months and dates, Dates are in valid range and first date falls before second.
#include <stdio.h>
int main()
{
int d,d1,d2,m,m1,m2,y,y1,y2;
printf("Enter first date (dd/mm/yyyy) : ");
scanf("%d/%d/%d,&d1,&m1,&y1");
printf("Enter the second date (dd/mm/yyyy) : ");
scanf("%d/%d/%d,&d2,&m2,&y2");
if(d2<d1)
{
if(m2==3)
{
if (y2%100!=0 && y2%4==0|| y2%400==0) // Checking leap year
d2+=29;
else
d2+=28;
}
else if (m2==5||m2==7||m2==10||m2==12)
d2+=30;
else
d2+=31;
}
if (m2<m1)
{
y2=y2-1;
m2+=12;
}
y=y2-y1;
d=d2-d1;
m=m2-m1;
printf("Difference of the two dates is : ");
printf("%d years,%d months,%d days\n",y,m,d);
return 0;
}
Upvotes: 0
Views: 49
Reputation: 26757
scanf("%d/%d/%d,&d1,&m1,&y1");
and
scanf("%d/%d/%d,&d2,&m2,&y2");
are wrong you must read the manual of scanf()
.
The first argument is the format string "%d/%d/%d"
and you must pass each address after: &d1, &m1, &y1
.
scanf("%d/%d/%d", &d1, &m1, &y1);
scanf("%d/%d/%d", &d2, &m2, &y2);
You should verify the return value of function:
if (scanf("%d/%d/%d", &d1, &m1, &y1) != 3) {
fprintf(stderr, "Something go wrong!");
return 1;
}
Upvotes: 2