Search code examples
arrayscnullstring-lengthnull-terminated

Input in Null terminating character array and getting its length


I hava a question.....I have a character array char command[30]. When I use it for input like if I entered !! on console the after input strlength function must give me length of array equals to 2 as it does not count null character. But It is giving me 3 as length of array. Why is it happening.

    char command[30];
    fgets(command,30,stdin);
    printf("%zu",strlen(command));

Solution

  • It's probably including the newline character - the Enter key.

    Try this to remove the newine character, then strlen should be as you expect:

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