簡體   English   中英

C程序strcmp無法正常工作

[英]C Program strcmp not working

我對為什么輸入沒有正確與“歷史記錄”進行比較感到困惑。 無論我鍵入什么,似乎都永遠不會進入if語句。 一旦輸入了history,就應該進入if語句。 我嘗試使用scanf(“%s \\ n”,input); 還可以看到,並且可以正常工作,但不是我想要的方式。

while(fgets(input, sizeof(input), stdin) != NULL){

    filePrint = fopen(".simpleshell_history", "a");
    fileRead = fopen(".simpleshell_history", "r");      

    count++;
    fprintf(filePrint, "%d - %s", count, input);
    fclose(filePrint);

    if (strcmp(input,"history")==0){
        printf("%s\n", input);
        fseek(fileRead, 0, SEEK_SET);
        int x = 0;
        while ((x = fgetc(fileRead)) != EOF){
            printf("%c", x); 
        }
    }
}

當您鍵入“ history \\ n”時,fgets()讀取並存儲換行符。 嘗試在if語句中使用strncmp(input,“ history”,7)或“ strcmp(input,” history \\ n“)。

fgets不會修剪輸入中的換行符。 使用strcmp之前,您需要自己進行此操作。

您可以通過執行以下操作來修剪它:

input[strlen(input) - 1] = '\0';

暫無
暫無

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

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