【发布时间】:2012-11-24 15:37:06
【问题描述】:
我必须在文件中搜索输入的字符串,但下面的代码不起作用。它总是说“在字典中找不到。文件(称为Dictionary.txt)的内容如下:
pow
jaw
pa$$word
代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30
main()
{
char inPassword[MAX + 1];
printf("\nEnter a password: ");
gets(inPassword);
printf("\n\nYou entered: %s, please wait, checking in dictionary.\n\n",inPassword);
checkWordInFile("Dictionary.txt",inPassword);
printf("\n\n\n");
system("pause");
}//end of main
void checkWordInFile(char *fileName, char *password);
{
char readString[MAX + 1];
FILE *fPtr;
int iFound = -1;
//open the file
fPtr = fopen(fileName, "r");
if (fPtr == NULL)
{
printf("\nNo dictionary file\n");
printf("\n\n\n");
system("pause");
exit(0); // just exit the program
}
while(fgets(readString, MAX, fPtr))
{
if(strcmp(password, readString) == 0)
{
iFound = 1;
}
}
fclose(fPtr);
if( iFound > 0 )
{
printf("\nFound your word in the dictionary");
}
else
{
printf("\nCould not find your word in the dictionary");
}
}
【问题讨论】:
-
为什么不为
iFound使用布尔值? -
也许他用 ANSI C 而不是 C99 编码。
-
你不应该是 int main( void ) 吗?
-
以防万一您对优化感兴趣:对于大量搜索,预排序字典和使用二分搜索 (O(log(n))) 或内存不是问题时会更快您可以散列所有字符串并在(O(1) 中进行预执行搜索,以获取较小的散列负载因子)。