When using the input hello world
to this program it outputs hell
which is less than 5 why does this happen
void grab_user_input()
{
char user_input[10];
if ( fgets(user_input, 5 , stdin ) != NULL )
{
printf("%s\n",user_input);
}
}
int main()
{
grab_user_input();
return 0;
}
CodePudding user response:
The last byte is the null byte \0
.
Read the fgets
manual for more info. Here's an excerpt:
char *fgets( char *restrict str, int count, FILE *restrict stream );
Reads at most
count - 1
characters from the given file stream and stores them in the character array pointed to bystr
. Parsing stops if a newline character is found, in which casestr
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 tostr
.