2015-04-06 52 views
0

我有以下代碼:ç簡單的拼寫檢查

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 

int main(int argc, char **argv){ 
    char c, word[100], dictionary[100]; 
    int h,k = 0, l = 0, size, i, right = 11, counter = 0; 
    char letter[2] = {0}; 
    FILE * file = fopen(argv[1], "r"); 
    FILE * dictionaryFile = fopen("american", "r"); 
    printf("Misspelled words in %s\n", argv[1]); 
    while(fscanf(file, "%s", word) != EOF){ 
     counter = 0; 
     k = 0; 
     while(fscanf(dictionaryFile, "%s", dictionary) != EOF){ 
      l = 0; 
      for(i = 0; i < strlen(word) - counter; i++){ 
       if(ispunct(word[i])){ 
        counter++; 
       } 
      } //here 
      while(word[k]){ 
       word[k] = tolower(word[k]); 
       k++; 
      } 
      while(dictionary[l]){ 
       dictionary[l] = tolower(dictionary[l]); 
       l++; 
      } 
      size = strlen(word) - counter; 
      word[size] = '\0'; 
      right = strcmp(word, dictionary); 

      if(right > 0 || right < 0){ 
       if(word[size - 1] == 's' || word[size - 1] == 'S'){ 
        word[size - 1] = '\0'; 
        right = strcmp(word, dictionary); 
        if(right > 0 || right < 0){ 
        } else { 
         counter++; 
        } 
       } 
      }else{ 
       counter++; 
      } 

     } 

     if(counter == 0){ 
      printf("%s\n", word); 
     } 
    } 
    fclose(dictionaryFile); 
    fclose(file); 
return 1; 
} 

我以一個命令行參數,它是我的文件,句子或單詞進行檢查。然後我檢查它們是否是一個名爲'american'的文件,它是一個字典文件。我知道可能有不少錯誤,我可以弄清楚,我遇到的問題是分段錯誤,因爲它會得到文件的第二個字。我測試了fscanf,它顯示了每個由空格分隔的單詞,並且正確地做了它,但現在我在第一個單詞之後出現了seg錯誤。我只是一個簡單的測試文件,說

hello tsting this checkr tests test. 

我從hello到tsting時遇到seg錯誤。正如我所說,我幾乎可以保證修復seg錯誤代碼仍然會有錯誤,在這一點上,我可以處理我只需要克服這個seg錯誤的錯誤。在我在else語句中添加counter ++之前,我沒有發現seg錯誤。我需要他們,我不明白他們爲什麼會造成錯誤。

回答

1

你似乎是使用可變counter三個相互矛盾的目的:

  • 它出現在終端狀態作爲減法表達式的右側。我認爲這與它下面的word[i]表達式相對應,是導致您崩潰的原因。
  • 在碰撞位置之前的循環中,您似乎將其用作標點計數器。
  • 在其他地方,您似乎正在使用它來計算字典文件中正確匹配的數量。

由於這些目的相互衝突,所以counter對於任何目的都變得毫無用處。你需要仔細考慮你打算如何處理counter,並確保你做到了這一點,只有這樣做。你爲什麼需要counter

strlen返回一個size_t類型,它是無符號的(不可能是負數)。假設counter大於strlen的返回值,那麼您可能會得到一個巨大的數字而不是負數。因此,您的循環可能會繼續遠遠超出word陣列的範圍,並導致未定義的行爲,這恰巧會導致崩潰。

+0

謝謝,我添加了一個新的計數器,並在代碼中進行了更改,它的工作原理,我現在只需要獲取正確的輸出。 – AndyPet74 2015-04-06 02:35:39