请帮帮我。我想知道为什么会这样。
这段代码没有给出正确答案:
#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;
}
Run Code Online (Sandbox Code Playgroud)
但这段代码给出了正确的答案。
#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;
}
Run Code Online (Sandbox Code Playgroud)
为什么?如何?
请帮助我任何知道为什么会发生这种情况的人。
当您像这样给予时,它不会忽略空格。
scanf("%c",&ch);
Run Code Online (Sandbox Code Playgroud)
当您将输入提供给第一个时,scanf您将提供enter('\n'). 它是一个字符,因此它将作为第二个字符的输入scanf。所以第二个输入不会得到用户的输入。
scanf(" %c",&ch);
Run Code Online (Sandbox Code Playgroud)
如果你这样给出,那么它会忽略那个空白字符,然后它会要求用户输入。