当只有两个 scanf 调用时,为什么这要求三个输入?

Why does this ask for three inputs when there are only two scanf calls?

下面的代码有两个 scanf 调用,但是当我 运行 它时,它要求三个输入。我假设问题来自 \n,但为什么呢?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *s,*t;
  s=malloc(1024);t=malloc(1024);
  scanf("%s\n",s);
  scanf("%s\n",s);
  if(s==t)
  {
    printf("Same!\n");
  }
  else
  {
    printf("Different\n");
  }
}

I assume the problem comes from \n, but why?

你是对的,这就是问题所在。

根据 scanf 的文档,格式字符串中的 \n 字符将导致 scanf 继续读取空白字符,直到遇到非空白字符。这意味着在你按下 ENTER 之后,scanf 会等待你输入一个非空白字符,但它只会在你按下 之后才会收到这个字符再次 ENTER(假设您的操作系统一次向您的程序发送一行输入)。这很可能不是您想要的。

如果你想读取单行输入,我建议你改用fgets

请注意,%s scanf 格式说明符只会读取输入的一个字,而 fgets 会读取整行输入。