将输入的数据存储在数组中 [英] Store data in array from input
问题描述
我是 C 的初学者.请不要介意我的问题是否蹩脚.在我编写的这个程序中,当我第一次使用 'for' 循环时,我希望只有 3 个值存储在一个数组中,但它存储了 4 个值,并且在下一个 'for' 循环中按预期显示了 3 个值.我的问题是为什么在第一个for"循环中它需要 4 个值而不是 3 个?
I'm beginner in C. Please dont mind if my question is lame. In this program which i have written, when I use 'for' loop first time , I expect only 3 values is stored in an array but it stores 4 values and in next 'for' loop as expected show 3 values. My Question is why in 1st 'for' loop it takes 4 values instead of 3?
#include<stdio.h>
void main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d\n",(marks+i));
}
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
}
推荐答案
\n
in scanf
是问题
#include<stdio.h>
int main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}
printf("\nEntered values:\n");
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
return 0;
}
原因:
我希望只有 3
个值存储在一个数组中,但它存储了 4 个值并在下一个for"循环中按预期显示 3 个值.我的问题是为什么在第一个for"循环中,它需要 4 个值而不是 3 个?
I expect only
3
values is stored in an array but it stores 4 values and in next 'for' loop as expected show 3 values. My Question is why in 1st 'for' loop it takes 4 values instead of 3?
第一:不,它只在数组marks[]
中存储3
数字而不是4
数字.
First: No, it only stores 3
number but not 4
numbers in array marks[]
.
第二:有趣的是理解循环只运行了 3 次,i = 0
到 i
i <;3
.for 循环根据条件运行.更有趣的代码被困在 scanf()
中,如下所述:
Second: interesting to understand loop runs only for three times for i = 0
to i < 3
. The for loop runs according to condition. More interesting code is stuck in scanf()
as described below:
您的困惑是为什么您必须输入四个数字,这不是因为您循环运行 4
次而是因为 scanf()
函数仅在您输入非-空格字符(在一些 enter 按下后,您输入一个非空格字符的数字符号).
Your confusion is why you have to enter four numbers, its not because you loop runs 4
times but its because scanf()
function returns only when you enter a non-space char (and after some enter press you inputs a number symbol that is non-space char).
要了解这种行为,请阅读手册:int scanf(constchar *format, ...);
:
To understand this behavior read manual: int scanf(const char *format, ...);
:
一系列空白字符(空格、制表符、换行符等;参见isspace(3)
).该指令匹配任意数量的空格,包括无,在输入.
A sequence of white-space characters (space, tab, newline, etc.; see
isspace(3)
). This directive matches any amount of white space, including none, in the input.
因为在第一个 for 循环中,在 scanf()
中,您已将 \n
包含在格式字符串中,因此 scanf()
仅在以下情况下返回按数字 enter(或非空格 键).
Because in first for loop's, in scanf()
you have included \n
in format string, so scanf()
returns only if press a number enter (or a non-space key).
scanf("%d\n",(marks+i));
^
|
new line char
会发生什么?
假设程序的输入是:
23 <--- because of %d 23 stored in marks[0] as i = 0
<enter> <--- scanf consumes \n, still in first loop
543 <--- scanf returns, and leave 542 unread,
then in next iteration 543 read by scanf in next iteration
<enter>
193
<enter> <--- scanf consumes \n, still in 3rd loop
<enter> <--- scanf consumes \n, still in 3rd loop
123 <--- remain unread in input stream
这篇关于将输入的数据存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!