0

Normaly strlen does not count the null terminator at the end of the string. But the below code prints the string count with the null terminator. Can anyone explain me why?

int main(){
    char name[100];
    fgets(name, 100, stdin);
    printf("length is : %d", strlen(name));
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 3
    It doesn't count the null character, it counts the trailing `\n`. Try `printf("<%s>", name);` and see what happens. Also read the documentation of [`fgets`](https://cplusplus.com/reference/cstdio/fgets/) closely. Also read this: https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input – Jabberwocky Oct 07 '22 at 07:17

1 Answers1

1

The function fgets can append to the entered string the new line character '\n'. So the function strlen counts this new line character.

From the C Standard (7.21.7.2 The fgets function)

2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

To remove the new line character from the string you can write

name[ strcspn( name, "\n" ) ] = '\0';

After that you can call the function printf using the conversion specifier zu instead of d (otherwise the call has undefined behavior).

printf("length is : %zu\n", strlen(name));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335