简体   繁体   中英

program does not read string with the defined length in fgets()

I found when I use the fgets function like so:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str[10];
    fgets(str, 5, stdin);

    printf("%s", str);
    system("PAUSE");

    return 0;
}

If I input a 123456789 , it will output a 1234 . That's 4 characters - not the 5 I have defined in the function. What is happening to the fifth character?

edit: title updated

that's because since C-strings are NUL terminated, fgets takes the string terminator ( \\0 ) into account, so if you pass a 5-char buffer, it is safe.

In your code, you should do:

fgets(str, sizeof(str), stdin);

since str is an array with known size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM