比较两个文本文件 - C中的拼写检查程序

时间:2011-12-14 21:57:43

标签: c string file-io while-loop

我正在编写拼写检查程序,将用户的文本文件与字典进行比较,以查看他们输入的单词是否在字典中。如果没有,则打印错误消息以告知用户特定单词是错误的。我已尝试过以下代码的多种变体,但未获得所需的结果。嵌套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;
}

1 个答案:

答案 0 :(得分:2)

解决此问题的通常方法是首先阅读字典并构建哈希表。然后,您将从输入文件中一次读取一个单词,如果散列表上不存在该单词,则标记错误。