From fgets manual page (https://linux.die.net/man/3/fgets):
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A terminating null byte (aq\0aq) is stored after the last character in
the buffer.
So it adds '\n'
after your 4 letters, returning string_length+1
.
From Removing trailing newline character from fgets() input you can add @Tim Čas solution to your code.
The line is still read with the fgets()
function and after we remove the newline character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char name[10] = { 0 };
printf("enter your name\n");
fgets(name, 10, stdin);
printf("your name is %s and it is %d letters\n", name, strlen(name)); // length problem
name[strcspn(name, "\n")] = 0;
printf("NEW - your name is %s and it is %d letters\n", name, strlen(name));
return 0;
}
That outputs:
enter your name
Andy
your name is Andy
and it is 5 letters
NEW - your name is Andy and it is 4 letters
Press any key to continue . . .