2012-11-24 129 views
2

我必須搜索文件以查找輸入的字符串,但下面的代碼不起作用。它總是說「無法在字典中查找的文件(稱爲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"); 
    } 


} 
+0

你爲什麼不使用'iFound'布爾值? –

+0

也許他用ANSI C而不是C99編碼。 – Joshua

+0

不應該主要是int main(void)嗎? –

回答

3

與fgets()離開\ n 。在弦上,除非EOF結束這種修復它:

while(fgets(readString, MAX, fPtr)) 
{ 
    size_t ln = strlen(readString); 
    if (ln && readString[ln-1] == '\n') { readString[ln-1] = 0; --ln; } 
    if(ln && strcmp(password, readString) == 0) 
    { 
     iFound = 1; 
    } 

} 
+0

很好。固定。 – Joshua

+0

和upvoted .... –

0

我將如何改變這個功能來搜索一個字符串,這個文件中包含例如如果我輸入一個單詞「repow234」我應該得到的消息?日這是不正確怎麼一回事,因爲「POW」是該文件,並不能用於

這不起作用:

while(fgets(readString, MAX, fPtr)) 
{ 
    if (strstr(password, readString) != NULL) 
    { 
     iFound = 1; 
    } 
} 

fclose(fPtr); 

if(iFound > 0) 
{ 
    printf("\nThis password cannot be used because it contains the word in the dictionary"); 
} 
else 
{ 
    printf("\nThis password can be used"); 
}