strcasecmp 未返回零值

3

我想知道为什么第一次使用strcasecmp()函数时返回0,但第二次使用时却不是。

在这个例子中,我特别将"hello world"输入标准输入。但它打印出来的不是0 0,而是0 10。我的代码如下:

#include "stdio.h"
#include "string.h"

int main(void) {

  char input[1000];
  char *a;

  fgets(input, 1000, stdin);

  a = strtok(input, " ");
  printf("%d\n",strcasecmp(a,"hello"));  //returns 0 

  a = strtok(NULL, " ");
  printf("%d\n",strcasecmp(a,"world"));  //returns 10


  return 0;
}

我做错了什么?

3
也许 a 会包含一个换行符。调试器可以确认这一点。 - Ed Heal
@EdHeal 我现在感觉很愚蠢。非常感谢你! - Flow-MH
1
请注意,在标准C中没有名为“strcasecmp()”的函数。您的标记需要指定(例如Linux)。 - Peter
如果不是重复的问题,与此相关 https://dev59.com/MnE95IYBdhLWcg3wOLQ1。 - alk
1个回答

6

在使用空格作为标记分隔符时,您在“hello world”后输入的新行符是“world”令牌的一部分。

如果您使用strtok(input, " \n");而不是strtok(input, " ");,程序将正确运行。实际上,您可能还想使用制表符作为标记分隔符。

整个程序如下:

#include "stdio.h"
#include "string.h"

int main(void) {

  char input[1000];
  char *a;

  fgets(input, 1000, stdin);

  a = strtok(input, " \n\t");
  if (a == NULL) return(-1);
  printf("%d\n",strcasecmp(a,"hello"));
  a = strtok(NULL, " \n\t");
  if (a == NULL) return(-1);
  printf("%d\n",strcasecmp(a,"world")); 


  return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接