[英]Compare two text files - spellchecking program in C
我正在编写一个拼写检查程序,该程序会将用户的文本文件与字典进行比较,以查看他们输入的单词是否在字典中。 如果不是,则会显示一条错误消息,告诉用户该特定单词是错误的。 我尝试了以下代码的多种变体,但未获得预期的结果。 它是嵌套的while循环中将其丢弃的东西。 这段代码处于起草阶段,我必须使其更高效地使用内存并进行整理。 我只是想让它先工作。 谢谢!
编辑:按照下面的提示略微更改了代码。 现在,它会读取第一个单词,并说它在词典中。 然后,它显示第二个单词,但字典扫描循环不运行,程序挂起。 我知道它的嵌套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;
}
解决此问题的通常方法是先阅读字典并构建哈希表。 然后,您一次要从输入文件中读取一个单词,如果哈希表中不存在该单词,则将其标记为错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.