The fgets()
function accepts the input when a newline character(Enter key when using stdin
) is encountered, and the newline character \n
is considered a valid character by the function and included in the string copied to your str2
.Hence when you pass it as a parameter to strlen()
it gives one more than the original number of characters in your string to account for the additional \n
character.
If you want the original number of characters or don't want a \n
to be added, use the gets()
function as it doesn't copy the newline character.And further, you only need to pass the string as argument,no need to pass the stream (stdin
) as the default stream for gets()
is stdin
.
char str2[100];
printf("\nEnter a string: ");
gets(str2);
printf("\n%d",strlen(str2));