Appatakardot
Appatakardot

Reputation: 23

Unexpected results from using 2 consecutive fgets in C

int main()
{

    char firstdate[10];
    char seconddate[10];    

    printf("Enter the First Date in this format:DD/MM/YYYY\n");
    fgets(firstdate , 11 , stdin);
    printf("Check: %s\n" , firstdate);



    printf("Enter the second Date in this format:DD/MM/YYYY\n");

    fgets(seconddate , 11 , stdin);
    printf("Check: %s\n" , seconddate);


    printf("second Check: %s\n" , firstdate);
    printf("second Check: %s\n" , seconddate);

    return 0;

}

Its a fairly simple program for now. As I expected, after the first call to fgets(), the input was stored in the char array firstdate. But after the second call to fgets(), the value in the firstdate char array seems to have gone missing. Not sure what is going on or why I get such results. Can you help me?

Results:

Enter the First Date in this format:DD/MM/YYYY
10/01/1997
Check: 10/01/1997

Enter the second Date in this format:DD/MM/YYYY
20/04/1995
Check: 20/04/1995

second Check:
second Check: 20/04/1995

Whats weird is that even though the array was too small to hold the contents, it initially was able to hold it correctly (As seen by the first output). Calling the second fgets function got rid of the value in 'firstdate' variable

Upvotes: 1

Views: 1066

Answers (1)

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

Your char[] are too small to hold what you read:

char firstdate[10]; // array of 10 bytes
fgets(firstdate, 11, stdin); // read 11 bytes

And, from fgets()'s man page:

Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a `\0' character is appended to end the string.

So you should declare arrays of size 13 and read 12 bytes (until a '\n' is found):

char firstdate[13];
char seconddate[13];
fgets(firstdate, 12, stdin);
fgets(seconddate, 12, stdin);

Upvotes: 2

Related Questions