我正在制作一个拼写检查程序,并且有一个可操作的代码,但确实需要改进。
问题1:我只想在比较字符串之前将字母数字字符读入wordcheck数组。我想摆脱所有特殊字符。我认为isalphnum将是最好的选择,但不确定如何实现它。
问题2:程序非常慢并且浪费了大量内存。我不知道怎么办呢。谁能给我一些指示?我迷失了使用二进制函数,这就是我确定我应该做的!这是我的代码:
#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 notfound;
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//
}
fseek(fp1,0,SEEK_SET);
/*printf("%s", wordcheck);//debugger*/
while(fscanf(fp1,"%s", worddict)!=EOF)
{
notfound = 1;
if(strcmp(wordcheck, worddict)==0)//compare strings//
{
printf("This word: %s is in the dictionary\n", wordcheck);//debugger//
notfound = 0;
break;
}
}
if(notfound == 1)
{
printf("%s is not in dictionary\n", wordcheck);
}
}
printf("Your file has been checked. Please check any errors found");
fclose(fp1);
fclose(fp2);
return 0;
}
答案 0 :(得分:0)
你正在为每个输入单词阅读一次字典!如果输入文件很长,则先将字典加载到内存中,然后检查文件中的每个单词。如果字典很长,您可能需要将其存储在哈希表或trie中。但是,即使是一个简单的字典单词数组也可以为你提供更好的运行时间。