可能重复:
比较两个文本文件 – C中的拼写检查程序
我正在编写一个拼写检查程序,它将用户的文本文件与字典进行比较,以查看他们输入的单词是否在字典中。
字典循环一次,然后它卡在最后的单词上。 我怎样才能再次遍历字典?
#include #include #include #include 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 %sn", userword); j=getc(fp2); while (dictword[j] != EOF) { fscanf(fp2, "%s", &dictword); /*printf("The first entry in the dictionary is %sn", 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 dictionaryn", userword);*/ } } } fclose(fp1); fclose(fp2); return 0; }
首先,我还建议使用像ddd (resp.GNU Debugger)这样的工具逐步执行代码。 在我看来,这是找到错误的最佳方法之一,因为您可以在执行期间观察所有变量的更改。
我看到的下一个问题是,你正在使用dictword
初始化的dictword
。 在第一次进入while循环之前,dictword [j]的内容是什么?
fseek(char *stream, long offset, int whence)
用于设置流的文件位置指示符。 还有一个名为rewind(char *stream)
的函数将位置指示器重置回文件的开头(两者都包含在stdio.h中 )。
有关详细信息,请尝试阅读相应的手册页 。
基本上你可以使用rewind(fp1);
在最后一个循环周期结束时(不要忘记适当地重置你的循环变量)。
希望我的问题是正确的;)。
这无法做任何事情的直接原因如下:
for (i=0; userword[i]; i++)
这里的条件循环是一个值,即索引i
处的char
值。 请注意,就目前而言,您的程序永远不会初始化此数组中的值(因此Basile Starynkevitch建议您使用警告进行编译,例如-Wall -Wextra)。
如果你得到任何输出,那只是一个侥幸。 userword []数组中的值可能会填充非零值,但在许多情况下它们也可能为零。 一个有趣的事情是,一些调试环境(例如gdb或MSVC)会故意用特殊值填充未初始化的内存区域,以便您更容易看到何时发生这种情况。 例如,见这个 。
Sangeeth Saravanaraj试图指出你正确的方向。 在那里的答案中,注意外部循环看起来像这样:
while(fscanf(fp2,"%s", wordcheck)!=EOF)//Reads word from text file into array//
这个循环在一个中完成两件事 – 它将一行从fp2
复制到wordcheck
,并检查此操作是否返回EOF
– 基本上表示我们在文件的末尾。 当我们结束时,它会从while循环中断开。
但是,简单地纠正你的for
循环并不能完全修复你的程序。 想想你如何循环遍历字典中的每个单词。 您的代码仅适用于单个“userdoc”单词,因为在单次通过字典后,您将位于该文件的末尾。 如果希望此方法起作用,则必须将所谓的文件指针重置为字典文件的开头:
while(fscanf(fp1,"%s", &userword)!=EOF){ printf("The word being checked is %sn", userword); fseek(fp2,0,0); while (fscanf(fp2, "%s", &dictword) != EOF) { ... }
以上就是c/c++开发分享实现拼写检查算法相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/519179.html