请查找以下代码示例
main()
{
int i;
char s[100];
printf("Enter the string \n");
scanf(" %s ",s);
printf("Enter the string\n");
scanf("%d",&i);
printf("%s\n%d\n",s,i);
}
上面代码的输出是
Enter the string
hai
hai
Enter the string
hai
0
它应该接受一行输入,但它也接受第二行。
如果删除 scanf 中的空格,则输出正确。
谁能解释一下吗?
当将相同的值与整数(%d)一起使用时,它不会发生。它发生在字符串上。
最佳答案
我们的第一个 scanf 等待一个开头包含空格的字符串,但它没有。因此它会要求您再次输入字符串,并且第二次会被接受,因为您在输入新字符串之前输入了 [enter]。 [enter] 在 scanf 中被视为空格。
引用这个链接,看起来是一样的
Explain what is difference between without whitespace in scanf and with whitespace in scanf?
关于c - scanf 获取带有空格的两行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12705218/