我不明白为什么我无法在 c 中获得三个输入
我的一个朋友正在尝试学习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
。
你能帮我理解为什么吗?
A friend of mine is trying to learn c (on her own, with a book) and sometimes she asks for help.
She just showed me something I can't answer; I'm ashamed but I studied C in college and then moved to php. I'm really stuck so I would like to know why we can't get three inputs. Here's partial code:
#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);
...
Like this it asks for the first input two times, like this:
Enter a number:
1
2
Enter another number:
3
Choose an operation sign:
-
If I remove the \n
it skips the last scanf
.
Can you help me understand why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以尝试使用
fflush
,但这取决于库实现(stdio)。可以在此处找到它的 C 参考。
稍后我会对此进行测试并更新我的帖子并说明它是否有效。
You can also try to use
fflush
, but it depends on the library implementation (stdio).The C reference for it can be found here.
I'll test this a bit later on and update my post and say whether it worked.
阅读此处: scanf() 将新行字符保留在buffer?
解决方案:
替代方案:
作为一个小注释,由于
scanf
的工作原理,使用这两种解决方案,您都可以直接在第一个“输入”中插入所有数据各种scanf
将参与其中。因此,您可以插入123 234 +
,它将正确拆分为三个变量。Read here: scanf() leaves the new line char in buffer?
Solution:
An alternative:
As a small note, thanks to how
scanf
works, with both the solutions you can insert directly in the first "input" all the data and the variousscanf
will take their part. So you could insert123 234 +
and it would be split in the three variables correctly.是的,
scanf
不会删除换行符,并且您无法刷新stdin
,那么这样怎么样:或者实际上是这样:
Yes,
scanf
does not remove the newline, and you can't flushstdin
, so how about this:or indeed this: