Strlen gives an incorrect output after fgets

烈酒焚心 提交于 2019-12-13 11:12:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!