strlen没有给出正确的字符串长度C.

我正在从我的字典中读取并打印出单词+单词的长度以用于测试目的。

我使用strlen来获取字符串的长度。 但是,我得到的数字不正确。 我相信strlen不计算\ 0字符。

我正在读字典中的前10个单词。 我的预期输出应该是:

W:AL:1 W:A's L:3 W:AA's L:4 W:AB's L:4 W:ABM's L:5 W:AC's L:4 W:ACTH's L:6 W:AI's L:3 W:AIDS's L:6 W:AM's L:4 

但这就是我得到的(请注意L:如何在另一条线上。我认为这就是问题所在):

 W:A L:2 W:A's L:4 W:AA's L:5 W:AB's L:5 W:ABM's L:6 W:AC's L:5 W:ACTH's L:7 W:AI's L:5 W:AIDS's L:7 W:AM's L:5 

以下是我的代码:

 FILE* dict = fopen("/usr/share/dict/words", "r"); //open the dictionary for read-only access if(dict == NULL) { return; } int i; i = 0; // Read each line of the file, and insert the word in hash table char word[128]; while(i < 10 && fgets(word, sizeof(word), dict) != NULL) { printf("W:%s L:%d\n", word, (int)strlen(word)); i++; } 

如果有足够的空间, fgets()换行符读入缓冲区。 因此,您会在打印word时看到打印的换行符。 从fgets手册:

fgets()从流中读取最多一个小于大小的字符,并将它们存储到s指向的缓冲区中。 阅读在EOF或换行后停止。 如果读取换行符,则将其存储到缓冲区中。 终止空字节(’\ 0’)存储在缓冲区中的最后一个字符之后。

(强调我的)

你必须自己修剪它:

 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++; } 

原因是因为fgets每次都会将换行符’\ n’拉入缓冲区word每次导致计数值增加1。