使用strcmp函数比较指针和字符串[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

这是我的代码:

  printf("Please input a command\n");

  char *input;
  input = malloc(sizeof(char) * 50);

  if(fgets(input, 50, stdin) != NULL) {
    if(strcmp(input, "end\0") == 0) {
      printf("END");
    }
  }

出于某种原因,当我输入'end'时,它不会打印“END”。这会导致循环条件失败的问题是什么? strcmp(input, "end\0") == 0当输入指针等于"end\0"时应返回0?我也试过strcmp(input, "end") == 0这也不起作用。我怎样才能解决这个问题?

c strcmp
2个回答
1
投票

fgets包括换行符。使用strcmp(input, "end\n")

从文档:

从流中读取字符并将它们作为C字符串存储到str中,直到读取(num-1)个字符或者到达换行符或文件结尾,以先发生者为准。

换行符使fgets停止读取,但它被函数视为有效字符,并包含在复制到str的字符串中。

并且如评论中所述,在使用字符串文字时,您不需要包含\0。无效终止将自动添加。


0
投票

您可以在比较字符串之前删除换行符\ r和\ n:

int length = strlen(input);

if(length>0 && input[length-1]=='\n') {
    input[length-1]='\0';
    length--;
}
if(length>0 && input[length-1]=='\r') {
    input[length-1]='\0';
    length--;
}

这段代码应该是windows linux和mac的通用代码。接下来,我在我的示例中使用了不安全的函数,如strlen和strcmp,还有strncmp只比较指定的字节数。

© www.soinside.com 2019 - 2024. All rights reserved.