I am very new to C and have written the following program. I believe there is a problem with my scanf function because the program crashes after entering the second date. Please review my code and advise where the problem lies. Thank you.
// Determine the number of days between two dates (year, month, and day)
# include <stdio.h>
int main ()
{
int stopit;
int a, b, c, d, e, f, n1, n2, diff;
printf ("Enter your first date - year (xxxx), month (xx), and day (xx) \n\n");
scanf ("%i %i %i ", &a, &b, &c);
if (b <= 02)
{
a = (a - 01);
b = (b + 13);
}
else
b = (b + 01);
n1 = (((1461 * a) / 4) + ((153 * b) / 5) + c);
printf ("\n\n");
printf ("n1 = %i\n", n1);
printf ("Enter your second date - year (XXXX), month (xx), and day (xx) \n\n");
scanf ("%i %i %i ", &d, &e, &f);
if (e <= 02)
{
d = (d - 01);
e = (e + 13);
}
else
e = (e + 01);
Change all of your scanf types from %i (I'm not even sure what i is) to %d (decimal integer (any negative/positive whole number including 0)). Tested and it works for me.
Make sure you replaced all 9 of them. The only other suggestion I have is to remove the spaces from the scanf types. The code was working perfectly for me after I just changed the %i's to %d's.
Edit: I compiled it with g++ so technically I ran it as C++ code. I doubt it would make a difference, but figured I would clarify.
Thank you all for your help. I have changed all %i to %d, but the program still crashes after the second date is entered.
Here is my revised program...
// Determine the number of days between two dates (year, month, and day)
# include <stdio.h>
int main ()
{
int stopit;
int a, b, c, d, e, f, n1, n2, diff;
printf ("Enter your first date - year (xxxx), month (xx), and day (xx) \n\n");
scanf ("%d%d%d ",&a,&b,&c);
if (b <= 2)
{
a = (a - 1);
b = (b + 13);
}
else
b = (b + 1);
n1 = (((1461 * a) / 4) + ((153 * b) / 5) + c);
printf ("\n\n");
printf ("n1 = %d\n", n1);
printf ("Enter your second date - year (XXXX), month (xx), and day (xx) \n\n");
scanf ("%d%d%d ",&d,&e,&f);
if (e <= 2)
{
d = (d - 1);
e = (e + 13);
}
else
e = (e + 1);