通过scanf在C中输入char

char Input in C by scanf

请帮帮我。 我想知道为什么会这样。

此代码未给出正确答案:

#include < stdio.h>

int main()

{

  char c,ch;

  int i;

    printf("Welcome buddy!\n\nPlease input first character of your name: ");
    scanf("%c",&c);

    printf("\nPlease input first character of your lovers name: ");
    scanf("%c",&ch);

    printf("\nHow many children do you want? ");
    scanf("%d",&i);

    printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);

  return 0;
}

但是这段代码给出了正确的答案。

#include < stdio.h>

int main()
{
  char c,ch;
  int i;

    printf("Welcome buddy!\n\nPlease input first character of your name: ");
    scanf(" %c",&c);

    printf("\nPlease input first character of your lovers name: ");
    scanf(" %c",&ch);

    printf("\nHow many children do you want? ");
    scanf("%d",&i);

    printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);

  return 0;
}

为什么? 以及如何?

请知道这是为什么发生的任何人帮助我。

当你这样给的时候,它不会忽略白色的spaces。

scanf("%c",&ch);

当您将输入提供给第一个 scanf 时,您将提供 enter('\n')。它是一个字符,因此它将作为第二个 scanf 的输入。所以第二个输入不会从用户那里得到输入。

scanf(" %c",&ch);

如果你这样输入,那么它会忽略那个白色的 space 字符,然后它会要求用户输入。

第一个程序无法正常运行,因为检查输入时的 scanf 函数在尝试解析字符时不会自动删除空格。
所以在第一个程序中,c 的值将是一个字符,而 ch 的值将是 '\n'(换行符)字符。
使用 scanf("\n%c", &varname);scanf(" %c", &varname); 将解析按回车键时插入的换行符。

scanf函数从标准输入流stdin.

读取数据

int scanf(const char *format, …); format 中的 white-space 字符,例如空格和换行符,导致 scanf 读取但不存储所有连续的 white-space 字符在输入中直到下一个不是白色的字符-space 字符。

现在,当您按 "a" 和 "return" 时,您在 stdin 流中有两个字符:a 和 \n字符。 这就是为什么第二次调用 scanf 将 \n 字符分配给 ch var.

您的 scanf() 函数从 stdin 获取输入。现在,当您从键盘上敲下任何字符并按下回车键时,您输入的字符会被 scanf() 扫描,但 enter 仍然存在于 stdin 中,它将被其下方的 scanf() 扫描。要忽略空格,您必须将 scanf() 与“ %c”一起使用。