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

strlen not giving correct string length C

我正在查字典并打印出单词 + 单词的长度以供测试。

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

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

W:A L: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() 如果有足够的 space,则将换行符读入缓冲区。因此,您会在打印 word 时看到换行符。来自 fgets 手册:

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 ('[=13=]') is stored after the last character in the buffer.

(强调我的)

你必须trim自己:

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

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

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