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");
    }


}
4

2 に答える 2

3

fgets() は、EOF でない限り、文字列の末尾に \n を残します。これで修正されます:

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;
    }

}
于 2012-11-24T15:49:51.277 に答える
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");
}
于 2012-11-28T17:54:16.117 に答える