May seem like a silly question for most of you, but I'm still trying to determine the final answer. Some hours ago I decided to replace all the scanf() functions in my project with the fgets() in order to get a more robust code. I learned that the fgets() automatically ends the inserted input string with the '\n' and the NUL characters but.. let's say I have something like this:
char user[16];
An array of 16 char which stores a username (15 characters max, I reserve the last one for the NUL terminator). The question is: if I insert a 15 characters strings, then the '\n' would end up in the last cell of the array, but what about the NUL terminator? does the '\0' get stored in the following block of memory? (no segmentation fault when calling the printf() function implies that the inserted string is actually NUL terminated, right?).
As a complement to 5gon12eder answer. I assume you have something like :
char user[16];
fgets(user, 16, stdin);
and your input is abcdefghijklmno\n
, that is 15 characters and a newline.
fgets
will put in user
the 15 (16-1) first characters of the input followed by a null and you will effectively get "abcdefghijklmno"
, which is what you want
But ... the \n
still remains in stream buffer an is actually available for next read (be it a fgets
or anything else) on same FILE. More exactly, until you do another fgets
you cannot know whether there was other characters following the o
.