簡體   English   中英

如何將用戶輸入與存儲在文件中的字符串進行比較?

[英]How can I compare user input to string stored into file?

我必須編寫一個文件處理代碼,它將從用戶收到的字符串與存儲在 C 文件中的 char 字符串進行比較。 我從昨天開始嘗試。 我不知道該怎么做。 我嘗試了很多東西,但似乎沒有任何效果。

//
//  2.c
//  IFTM Exercises
//
//  Created by Lelre Ferreira on 10/27/19.
//  Copyright © 2019 Lelre Ferreira. All rights reserved.
//

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

int main (int argc, const char * argv[]){

    FILE *file = fopen("file.txt", "w");
    char text[] = "hi hi hi hi hi hi"; //string to be allocated into the file
    char c, userInput[] = "hi"; // simulates the user input
    int i = 0, count = 0;



    if (file == NULL) {
        printf("Failure to create file.\n");
        exit(1);
    } else {
        for (i = 0; i < strlen(text); i++) {
            printf("Inserting: [%c]\n", text[i]);
            fputc(text[i], file);
        }
        printf("All done.\n");
    }
    fclose(file);


    fopen("file.txt", "r");
    while ((c = fgetc(file) != EOF)){
        fscanf(file,   "%s",   text);
        if (strcmp(userInput, text) == 0) {
            count++;
        }
    }
    fclose(file);



    printf("Many times present: %d\n", count);
    return 0;
}

我的問題是......文件中字符串的每個單詞之間的空格,因為我必須檢查是否有另一個單詞開頭,例如......(嗨嗨)......我想過在我的代碼,但我沒有工作。

while ((c = fgetc(file) != EOF)){ // While the end of the file does not happen keep running.
    if ((c = fgetc(file) != ' ')) { //If an blank space is found... I does not make any sense actually. I'm desesperated.
        strcmp(userInput, text){
            count++
        }
    }
}
while ((c = fgetc(file) != EOF)){ 
    if ((c = fgetc(file) != ' ')) { 
        strcmp(userInput, text){
            count++
        }
    }
}

這里存在三個主要問題。

首先, c = fgetc(file) != EOFc = (fgetc(file) != EOF)相同,這顯然不是你想要的。 它應該是(c = fgetc(file)) != EOF

其次,上面的語句(假設你沒有得到 EOF)實際上讀取了一個字符。 所以 if 語句應該是if(c != ' ')

三、 c需要聲明為int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM