问题
I read a string using fgets. It prints correctly but if i try to output the length using a strlen or a while until NULL it returns a bad value. Does fgets not end the string with NULL?
char word[256];
fgets(word, sizeof(word), stdin);
while(word[i])
i++;
printf("%d",i);
For the string aba it outputs 40.
回答1:
Function fgets
also includes the new line character in the string. So function strlen
counts this symbol.
From the C Standard
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.
回答2:
The below code outputs proper value:
int main()
{
char word[256];
int i =0;
fgets(word, sizeof(word), stdin);
while(word[i])
i++;
printf("%d\n",i);
}
来源:https://stackoverflow.com/questions/26831846/strlen-gives-an-incorrect-output-after-fgets