【问题标题】:C Program strcmp not workingC程序strcmp不工作
【发布时间】:2013-12-08 10:31:21
【问题描述】:

我有点困惑为什么输入没有正确地与“历史”进行比较。无论我输入什么,它似乎都不会进入 if 语句。一旦我输入历史,它就会进入 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); 
        }
    }
}

【问题讨论】:

  • fgets 在缓冲区末尾留下一个换行符。
  • 换行符包含在input
  • 感谢您的帮助!就是这样。

标签: c linux unix strcmp


【解决方案1】:

当您键入“history\n”时,fgets() 会读取并存储换行符。尝试在 if 语句中使用 strncmp(input, "history", 7) 或 "strcmp(input, "history\n")。

【讨论】:

  • 谢谢!特别是对于简单的修复! :)
【解决方案2】:

fgets 不会从输入中修剪换行符。在使用 strcmp 之前,您需要自己执行此操作。

您可以通过执行以下操作来修剪它:

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

【讨论】:

  • 假设strlen(input) 至少为1
  • 感谢您的帮助!这就是问题所在。
猜你喜欢
  • 2016-06-23
  • 2010-12-29
  • 2010-11-01
  • 2016-02-24
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多