簡體   English   中英

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()換行符讀入緩沖區。 因此,您會在打印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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM