gpt4 book ai didi

c - 实现拼写检查算法

转载 作者:行者123 更新时间:2023-11-30 19:50:04 25 4
gpt4 key购买 nike

Possible Duplicate:
Compare two text files - spellchecking program in C

我正在编写一个拼写检查程序,它将用户的文本文件与字典进行比较,以查看他们输入的单词是否在字典中。

字典循环一次,然后卡在最后一个单词上。如何再次循环浏览字典?

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

int main (void)
{
FILE * fp1, *fp2; /* file handle */
char userword[100];
char dictword[100];
char fname[40];
int i, j, ca, cb;

// printf("Enter filename to compare to dictionary:");
// fgets(fname,40,stdin);
// fp1 = fopen(fname,"r");
fp1 = fopen("userdoc.txt", "r"); /* open file for reading, use for
* time being until name input resolved*/
fp2 =fopen("dictionary.txt", "r");

if (fp1 == NULL)
{
printf("Could not open file for output.\n");
return 0;
}
if (fp2 == NULL)
{
printf("Cannot open %s for reading \n", fname);
exit(1); // terminate program
}

for (i=0; userword[i]; i++)
{
fscanf(fp1, "%s", &userword);
printf("The word being checked is %s\n", userword);

j=getc(fp2);
while (dictword[j] != EOF)
{
fscanf(fp2, "%s", &dictword);
/*printf("The first entry in the dictionary is %s\n", dictword); //check if dictionary is looping*/

if(strcmp(dictword, userword) == 0)
{
printf("you spelt \"%s\" correctly \n", dictword);
break;
}
else
{
/*printf("sorry \" %s \" is not in the dictionary\n", userword);*/
}
}
}
fclose(fp1);
fclose(fp2);
return 0;
}

最佳答案

首先,我还建议使用类似 ddd 的工具逐步执行代码。 (分别是 GNU 调试器)。在我看来,这是查找错误的最佳方法之一,因为您可以在执行过程中观察所有变量的变化。

我看到的下一个问题是,您使用的是未初始化的dictword。第一次进入 while 循环之前 dictword[j] 的内容是什么?

fseek(char *stream, long offset, int wherece) 用于设置流的文件位置指示符。还有一个名为 rewind(char *stream) 的函数,用于将位置指示器重置回文件的开头(两者都包含在 stdio.h 中)。

有关更多信息,请尝试阅读相应的 man pages .

基本上,您可以在最后一个循环周期结束时使用 rewind(fp1); (不要忘记适本地重置循环变量)。

希望我的问题是正确的;)。

关于c - 实现拼写检查算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8580222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com