1

Cの関数で状況が発生してstrncmpいます。単語が一致しない場合でも0を返します。以下の例では、文字「R」でテストしています。コードを実行すると、比較された単語が一致しても0が返されますtxtドキュメントでは「RUN」です。あなたはたまたま知っていますか?

strncmp 関数またはコード内の他の場所に何か不足していますか?

ご意見ありがとうございます。


bool lookup(string s);

int main(void) {

char *s;
s = "R";
if (lookup(s)) {
    printf("Word found =)\n");
} else {
    printf("Word not found =(\n");
}
}

// Looks up word, s, in txt document.
bool lookup(string s)
{
 // TODO
    char *wordtosearch;
    wordtosearch = s;
    int lenwordtosearch = strlen(wordtosearch);
    char arraywordindic[50];

// Open txt file
FILE *file = fopen("text.txt", "r");
if (file == NULL)
{
    printf("Cannot open file, please try again...\n");
    return false;
}

while (!feof(file)) {
    if (fgets(arraywordindic, 50, file) != NULL) {
        char *wordindic;
        wordindic = arraywordindic;
        int result = strncmp(wordindic, wordtosearch, lenwordtosearch);
        if (result == 0) {
            printf("%i\n", result);
            printf("%s\n", wordindic);
            printf("%s\n", wordtosearch);
            fclose(file);
            return true;
        }
    }        
}
fclose(file);
return false;
}
4

2 に答える 2