2015-04-06 55 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