Given the definition of fgets()
:
char *fgets( char *str, int count, FILE *stream );
(until C99)
char *fgets( char *restrict str, int count, FILE *restrict stream );
(since C99)
Reads at most count - 1
characters from the given file stream and stores them in the character array
pointed to by str
. Parsing stops if a newline
character is found, in which case str
will contain that newline
character, or if end-of-file
occurs. If bytes are read and no errors occur, writes a null character
at the position immediately after the last character written to str
.
The behavior is undefined if count
is less than 1. It is also not specified whether a null
character is written if count==1
.
fgets
stores the inputed line with the maximum length (size) of 5 in the str
variable and null terminates it.
Since the size you provide is 5, if you input "Hello"
it will store H e l l \0
replacing the 'o'
, 'o'
is not stored and, normally, 'o'
and '\n'
will remain in the stdin
buffer though this is not standard mandated.
If you intput "Hell"
the stdin
buffer will have H e l l \n
so when its stored '\n'
will be replaced by '\0'
, and '\n'
will remain in the buffer.
In the same way if the line is smaller than 5 - 1
, nothing is replaced, the char array
is null terminated i.e. "Hel"
will be stored as H e l \n \0
, and the stdin
buffer will be emptied.
This is why you normally declare your char array
1 char bigger than the actual max size expected, and pass its size to fgets
:
fgets(str, sizeof(str), stdin);
Note that you should not use fflush(stdin).