[英]Multiple inputs in a single line using scanf()?
I used scanf()
function and realized that I could input only one number into an array using it. 我使用
scanf()
函数,并意识到只能使用一个数字输入一个数字。 Is there any way to read the whole number in a single line? 有没有办法单行读取整数?
ex: 例如:
for(i=0;i<5;i++)
{
scanf("%d",&arr[i]);
}
I wanted to read all the 5 digits in a single line.. Hope I'm clear enough! 我想单行读取所有5位数字。.希望我足够清楚!
If you mean a single source code line, you could use either: 如果您指的是单个源代码行,则可以使用以下任一方法:
scanf ("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);
or: 要么:
for (i = 0; i < 5; i++) scanf ("%d", &(arr[i]));
If you meant a single input line, both those are fine as well. 如果您要输入的是一条输入线,那么两者都很好。 The
%d
will skip leading white space in the stream so it makes little difference whether you enter: %d
将跳过流中的前导空白,因此无论您输入以下内容,它都没有太大区别:
1 2 3 4 5
or: 要么:
1
2
3 4
5
I prefer the loop version myself since it can be made arbitrarily large without making your source code line way too long. 我本人更喜欢循环版本,因为它可以任意增大而不会使源代码行太长。
Though you want it in array . 虽然你想要它在array中。 A number of
5
digits can be stored in single int
variable (depending on what is size of int
on your system). 单个
int
变量中可以存储5
位数字(取决于系统上int
大小)。
In a single scanf
you can do this - 在一个
scanf
您可以执行以下操作-
scanf("%d %d %d %d %d",&a[0],&a[1],&a[2],&a[3],&a[4]);
This - 这个 -
for(i=0;i<5;i++)
{
scanf("%d",arr[i]); //you missed & should be scanf("%d",&arr[i]);
}
您可以使用scanf ("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.