Reputation: 1
I am doing the exercises in "Programming in C" book, 3rd Edition, by Steven G.Kochan. Currently working on Chapter 9 -Working with structs. The main part of the question is below, the formula in the code was provided in the question:
Write a program that permits the user to type in two dates and then calculates the number of elapsed days between the two dates.Try to structure the program logically into separate functions. For example, you should have a function that accepts as an argument a date structure and returns the value of N. This function can then be called twice, once for each date, and the difference taken to determine the number of elapsed days.
The code I have written is also below....but it is not working as it should: I have an image attached as proof please help me figure out what the issue is output screen showing that it doesn't allow me enter the second date.
#include <stdio.h>
struct date
{
int day;
int month;
int year;
};
//function declarations
int f (struct date thisDate);
int g (struct date thisDate);
int main(void)
{
//declarations and initializations
struct date theDate, otherDate;
int N1, N2, days;
printf("Enter the first Date (dd/mm/yyyy):");
scanf("%i/%i/%i", &theDate.day, &theDate.month, &theDate.year);
// compute N1
N1 = (1461 * f(theDate) ) / 4 + (153 * g(theDate)) / 5 + 3; //this can be replaced with a function
printf("\nEnter the second Date (dd/mm/yyyy):");
scanf("%i/%i/%i", &otherDate.day, &otherDate.month, &otherDate.year);
// compute n2
N2 = (1461 * f(otherDate) ) / 4 + (153 * g(otherDate)) / 5 + 3; //this can be replaced with a function
days = N2 - N1;
printf("\nThere are %i days between these two dates",days);
return 0;
}
int f (struct date thisDate)
{
if (thisDate.month <= 2)
{
return thisDate.year - 1;
}
else
{
return thisDate.year;
}
}
int g (struct date thisDate)
{
if ( thisDate.month <= 2)
{
return thisDate.month + 13;
}
else
{
return thisDate.month + 1;
}
}
Upvotes: 0
Views: 62
Reputation: 755094
Looking at the image, the input string is 03/09/2007
; the second input doesn't wait for anything new to be entered before doing the calculation.
The problem is that you used %i
which reads octal, hexadecimal or decimal numbers. Octal numbers are indicated by a leading zero; 09
therefore translates to a 0
for the month (because 9
is not a valid octal digit; 08
would also give problems) and then fails the conversion (no /
after that 0. The next input starts with the 9
and the 2007
and then doesn't find a /
so it stops.
Multiple morals:
scanf()
. In this code, make sure it returns 3; if not, something has gone wrong.%i
to read date values; use %d
. People don't use octal, and they do enter 09
(and 08
) on occasion.Upvotes: 1