The character array name
is declared with 10
elements
char name[10];
If you are using the following call of fgets
fgets(dog.name, 10, stdin);
after entering 10
characters 'a'
then the fgets call reads only 9
characters from the input buffer and appends the array with the terminating zero character '\0'
.
So the array will contain the string "aaaaaaaaa"
. It is the same as to initialize the array the following way
char name[10[ = { 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', '\0' };
After that the input buffer will contain one character 'a'
and the new line character '\n'
. These characters will be read by the next call
fgets(dog.breed, 10, stdin);
As result the array bread
will contain the string "a\n"
.
It is the same as to initialize the array the following way
char bread[10[ = { 'a', '\n', '\0' };
If you want to store in the arrays strings with more characters you should enlarge the arrays.
For example if you want to enter for the array name a string of 10
characters 'a'
you have tfo declare the array as having 12
elements. Why 12
? Because apart from 10
characters 'a'
and the terminating zero character the function fgets
also will try to read the new line character '\n'
from the input buffer. Otherwise this character will be read by a second call of fgets
.
To remove the new line character from an array you can use the following approach
#include <string.h>
//...
fgets( dog.name, 12, stdin );
dog.name[strcspn( dog.name, "\n" )] = '\0';