从输入中将数据存储在数组中

ran*_*jun 6 c arrays

我是C的初学者.如果我的问题很蹩脚,请不要介意.在我编写的这个程序中,当我第一次使用'for'循环时,我预计只有3个值存储在一个数组中,但它存储了4个值,并且在下一个'for'循环中,如预期的那样显示3个值.我的问题是为什么在第一个'for'循环中它需要4个值而不是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));
    }
}
Run Code Online (Sandbox Code Playgroud)

San*_*oel 11

\n在这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;
}
Run Code Online (Sandbox Code Playgroud)

原因:

我希望只有3值存储在一个数组中,但它存储4个值,并在下一个'for'循环中按预期显示3个值.我的问题是为什么在第一个'for'循环中它需要4个值而不是3个?

第一: 不,它只存储3数字而不是4数字marks[].

第二:有趣的理解循环只运行三次i = 0i < 3.for循环根据条件运行.更有趣的代码scanf()如下所述:

你的困惑是为什么你必须输入四个数字,这不是因为你循环运行4时间而是因为scanf()函数仅在你输入非空格字符时返回(并且在一些enter按下之后输入一个非空格字符的数字符号).

要了解此行为,请阅读手册int scanf(const char *format, ...);:

一系列空格字符(空格,制表符,换行符等;请参阅参考资料 isspace(3)).该指令 在输入中匹配任意数量的空白,包括无空格.

因为在第一个for循环中,在 scanf()你已经包含\n在格式字符串中,所以scanf()只有在按下数字enter(或非空格key)时才返回.

 scanf("%d\n",(marks+i));
           ^
           |
            new line char 
Run Code Online (Sandbox Code Playgroud)

怎么了?

假设对程序的输入是:

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 
Run Code Online (Sandbox Code Playgroud)

  • 从[`int scanf(const char*format,...);`](http://www.cplusplus.com/reference/cstdio/scanf/)读取**参数**/如果格式字符串是**空格字符:**itd返回*`格式字符串中的单个空格验证从流中提取的任何数量的空白字符(包括无).*所以当@ranaarjun在scanf中使用`\n`时,它总是等待读取一个`\n`甚至在最后一个数字输入之后,因为`\n`可以消耗任何数量的`\n`,因为我引用,直到**OP**不输入非同时的char(他实际输入的数字)然后)scanf不会从输入流中读取 (4认同)