Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fgets reads 4 charachters when buffer is 5

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading