1

入力を一般的な単語の辞書と照合し、入力がpassHistoryファイルに保存されている以前の入力と一致するかどうかを確認する次のコードがあります。私の問題は、Cの文字列を比較するstrcmpメソッドが正しく実行されていないように見えることです。私のコードでは、passHistoryで使用されている一般的な単語または入力がすでに使用されている場合、適切なエラーが表示されないためです。

いくつかのガイダンスをいただければ幸いです。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define MAX 30
#define gC_FOUND 99
#define gC_NOT_FOUND -99


int checkWordInFile(char * fileName,char * theWord);



int main()
{

    char userString[MAX + 1];

    int iResult;

    printf("Enter your string: ");
    gets(userString);


    printf("\n\nYou entered: %s, please wait, checking in dictionary.\n\n", userString);
    iResult = checkWordInFile("dictionary.txt",userString);




    if( iResult == gC_FOUND )
    {
        printf("\nFound your word in the dictionary");
    }
    else
    {
        printf("\nCould not find your word in the dictionary");
    }

    iResult = checkWordInFile("passHistory.txt",userString);
    if( iResult == gC_FOUND )
    {
        printf("\nPassword used");
    }
    else
    {
        printf("\nOk to use!");
    }

    printf("\n\n\n");
    system("pause");

} /* end of main */

int checkWordInFile(char * fileName,char * theWord){

    FILE * fptr;
    char fileString[MAX + 1];
    int iFound = -99;
    //open the file
    fptr = fopen(fileName, "r");
    if (fptr == NULL)
    {
        printf("\nNo dictionary file\n");
        printf("\n\n\n");
        system("pause");
        return (0); // just exit the program
    }

    /* read the contents of the file */
    while( fgets(fileString, MAX, fptr) )
    {
        if( 0 == strcmp(theWord, fileString) )
        {
            iFound = -99;
        }
    }

    fclose(fptr);

    return(0);



}//end of checkwORDiNFile
4

1 に答える 1

3

fgets()改行文字が検出された場合は、それが入力しているバッファーに書き込みます。使用する前にそれを削除してstrcmp()ください:

char* new_line = strrchr(fileString, '\n');
if (new_line) *new_line = 0;

gets()これは、入力の境界チェックがないため危険なAPIであり、バッファオーバーランが発生する可能性があることに注意してください。ユーザー入力を読み取るためのより安全なメカニズムは、fgets()または指定子scanf()を使用して、読み取る最大文字数を指定します。ヌルターミネータを使用できるようにするには、配列のサイズより1つ小さくする必要があります。%NsNN

scanf("%30s", userString);

文字列がファイル内で見つかった場合、不要な処理を回避するために、breakからファイルの残りの部分を検索し続ける理由はありません。sの値は、内で変更されることはなく、戻り値として使用されないことwhileに注意してください。常に返されます。私はあなたがループ内を意味したと思います。また、見つかったものと見つからなかったものを示すマクロを定義しましたが、関数内でこれらを使用せず、ハードコードされた値を使用します。iFoundcheckWordInFile()0iFound = gC_FOUND;

于 2012-11-21T19:10:25.703 に答える