strlen not giving correct string length C

こ雲淡風輕ζ 提交于 2019-12-05 07:46:15

fgets() reads in the newline into the buffer if there's enough space. As a result, you see the newline printed when you print word. From the fgets manual:

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 ('\0') is stored after the last character in the buffer.

(emphasis mine)

You have to trim it yourself:

while(i < 10 && fgets(word, sizeof(word), dict) != NULL) {
  size_t len = strlen(word);
  if ( len > 0 &&  word[len-1] == '\n' )  word[len] = '\0';

  printf("W:%s L:%d\n", word, (int)strlen(word));
  i++;
}

The reason is because fgets pulls the newline character '\n' into your buffer word each time, leading to a higher count by 1 each time.

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