c - 使用函数 strcmp 比较指针和字符串

标签 c strcmp

这是我的代码:

  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这也行不通。我该如何解决这个问题?

最佳答案

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

来自文档:

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

正如评论中提到的,您不需要包含 \0当使用字符串文字时。将自动添加空终止符。

关于c - 使用函数 strcmp 比较指针和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47857697/

相关文章:

c - 汇编代码会忽略 const 关键字吗?

c - 使用 realloc 动态增长结构数组会导致堆损坏

c++ - 在动态分配的内存上调用 memset 会导致堆损坏吗

c - strcmp 表示看似相同的字符串不相等

linux - strcmp 用法错误?

c - 从不兼容的指针类型传递参数 1( 'strcmp')

c - 在 C 中不使用函数原型(prototype)有什么好处吗?

c - 在 C 中移动多维数组指针 - 不兼容的类型

c++ - 如何在此代码中正确使用 strcmp() ?

使用 strcmp 比较 C 字符串和 char