[英]Reading multiple values in C using scanf
There is another thread explaining the way to get multiple values using scanf().还有另一个线程解释了使用 scanf() 获取多个值的方法。 I tried that, however, I got correct value for the first variable and junk values for the remaining two variables.
我试过了,但是,我得到了第一个变量的正确值和其余两个变量的垃圾值。 When I used separate scanf statements, it worked fine.
当我使用单独的 scanf 语句时,它工作得很好。 I am using RH Linux 5. Kernel version - 2.6.18-238.
我正在使用 RH Linux 5. Kernel 版本 - 2.6.18-238。 4.1.2
4.1.2
eg if I do scanf("%d %d %d",&n,&p1,&p2)
, then n is read fine.例如,如果我执行
scanf("%d %d %d",&n,&p1,&p2)
,则 n 读取良好。 But p1 is assigned 32767 and p2 is assigned another number even after I read the values.但是 p1 被分配了 32767 并且 p2 被分配了另一个数字,即使在我读取了这些值之后。 But according to the thread on SO, it should work.
但是根据SO上的线程,它应该可以工作。 So what am I doing wrong?
那么我做错了什么?
You don't say what types the three variables are.你没有说这三个变量是什么类型。 They have to be
int
.他们必须是
int
。
The following code works as expected on my computer:以下代码在我的计算机上按预期工作:
#include <stdio.h>
int main()
{
int n, p1, p2;
scanf("%d %d %d", &n, &p1, &p2);
printf("%d %d %d\n", n, p1, p2);
return 0;
}
Here is the output:这是 output:
$ gcc x.c
$ ./a.out
10 3 5
10 3 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.