2011-12-14 20 views
-1

我正在編寫一個拼寫檢查程序,它將用戶的文本文件與字典進行比較,以查看它們輸入的單詞是否在字典中。如果沒有,則會打印一條錯誤消息,告訴用戶該特定單詞是錯誤的。我已經嘗試了以下代碼的一些變體,但沒有得到想要的結果。這是在嵌套的while循環中拋出它的東西。這段代碼正處於草稿階段,我不得不提高內存的使用效率,並整理它。我只是想讓它先工作。謝謝!比較兩個文本文件 - C中的拼寫檢查程序

編輯:根據下面的提示稍微改變了代碼。現在它讀取第一個單詞並且說它在字典中。然後顯示第二個單詞,但字典掃描循環不運行,程序掛起。我知道它的嵌套while循環造成的問題,我無法讓我的頭在附近!

/*Spellcheck program*/ 
/*Author: */ 

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

int main(void) 
{ 
/*Open files and test that they open*/ 
FILE *fp1; 
FILE *fp2; 
char fname[20]; 
char wordcheck[45];/*The longest word in the English Language is 45 letters long*/ 
char worddict[45]; 
char dummy; 
int i; 
int dictcount = 0; 

fp1 = fopen("dictionary.txt","r"); 

if (fp1 == NULL) 
{ 
printf("The dictionary file did not open."); 
exit(0); 
} 

printf("Please enter the path of the file you wish to check:\n"); 
scanf("%s", fname); 
scanf("%c", &dummy); 

fp2 = fopen(fname, "r"); 
    if (fp2 == NULL) 
     { 
     printf("Your file did not open, please check your filepath and try again.\n"); 

     printf("Please enter path of file you wish to check: \n"); 
     scanf("%20s",fname); 

     fp2 = fopen(fname, "r"); 
     } 

    else 
     { 
     printf("Your file opened correctly\n"); 
     } 

/*When files are open, read each word from the text file into an array:*/ 

    while(fscanf(fp2,"%s", wordcheck)!=EOF)//Reads word from text file into array// 
    { 

     for (i=0; wordcheck[i]; i++) 
     { 
      wordcheck[i] = tolower(wordcheck[i]);//makes all characters lower case// 
     } 

     printf("%s", wordcheck); 

     while(dictcount >= 0)//reads dictionary word into array// 
     { 
      dictcount = 0; 
      fscanf(fp1,"%s", worddict); 

      if(strcmp(wordcheck, worddict)==0)//compare strings// 
      { 
      printf("This word: %s is in the dictionary\n", wordcheck); 
      break; 
      } 

      else 
      { 
      dictcount++; 
      } 

      if(worddict == NULL) 
      { 
      printf("Your word: %s is not in the dictionary\n", wordcheck); 
      } 
     } 
     dictcount++; 
    } 
    fclose(fp1); 
    fclose(fp2); 

return 0; 
} 
+0

請不要關閉。這傢伙有天賦。 – wildplasser 2011-12-14 22:16:09

+0

感謝您輸入wildplasser。我得到你說的重新函數,並不掃描直到文件結束,但我在真正的strcmp下休息。這不足以停止掃描到EOF嗎? – adohertyd 2011-12-14 22:24:46

回答

2

解決此問題的常用方法是首先閱讀字典並構建散列表。然後,您將從輸入文件中一次讀取一個單詞,並在散列表中不存在單詞時標記錯誤。