【发布时间】:2011-10-19 09:05:42
【问题描述】:
我的一个朋友正在尝试学习 c(她自己,用一本书),有时她会寻求帮助。
她只是向我展示了一些我无法回答的东西;我很惭愧,但我在大学学习了 C,然后转到了 php。我真的被困住了,所以我想知道为什么我们不能得到三个输入。这是部分代码:
#include <stdio.h>
int main()
{
int num1;
int num2;
char x;
printf("Enter a number:\n");
scanf("%d\n",&num1);
printf("Enter another number:\n");
scanf("%d\n",&num2);
printf("Choose an operation sign:\n");
scanf("%c\n",&x);
...
像这样它会要求第一个输入两次,像这样:
Enter a number:
1
2
Enter another number:
3
Choose an operation sign:
-
如果我删除\n,它会跳过最后一个scanf。
你能帮我理解为什么吗?
【问题讨论】:
-
请注意,使用上面的示例输入,您会得到
num1 == 1、num2 == 2、x == '3'。 -
如果删除\n,程序不会跳过最后一个scanf。相反,scanf 仍留在缓冲区中的 \n 被存储在变量 x 中。