为什么scanf的要求输入两次,只是仅在第一循环迭代? [英] Why does scanf ask for input twice, but just in the first loop iteration only?

查看:408
本文介绍了为什么scanf的要求输入两次,只是仅在第一循环迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这似乎与重复这个问题,但对我来说,为什么这个只有在发生第一循环迭代(对于1个数组元素输入)。不是所有的,为什么?

First of all, this may seem duplicate with this question, but in my case, why did this only happen in the 1st loop iteration (input for the 1st array element). Why not all?

我的code:

#include "stdio.h"

int main(int argc, char const *argv[])
{
    int a[5];
    int i;
    for (i = 0; i < 5; i++) {
        printf("Input a[%d]:\n", i);
        int x = scanf("%d ", &a[i]);    // notice the white-space after %d
    }
    for (i = 0; i < 5; ++i)
    {
        printf("a[%d]=%d\n", i, a[i]);
    }
}

输出例如:

Input a[0]:
1
2
Input a[1]:
3
Input a[2]:
4
Input a[3]:
5
Input a[4]:
6
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5

为什么会要求输入只有两次为 A [0] ,但不是为了休息,也是为什么分配到的值[ 1-5] 是在一个循环迭代前输入值吗?

Why did it ask for input twice only for a[0] but not for the rest, and also why the value assigned to a[1-5] is the value that was input in the one loop iteration before it?

我看了的答案,但我还是不中的每个明白为什么它没有要求输入两次循环。任何明确的解释?

I read this answer, but I still don't understand why it didn't ask for input twice in each loop. Any clear explanation?

推荐答案

在你的情况,

 scanf("%d ", &a[i]);

之后的扫描的整数, scanf()的需要白色的空间,任何数量的空格匹配,直到非空格字符才能完成比赛。

after scanning an integer, scanf() needs to match the white space, and any number of white space until a non-white space character is required to complete the match.

因此​​,对于第一次,第二输入是所述非白色空间,这将终止的扫描的,而是留在缓冲液(保持未读)为下一个的扫描

So, for the first time, the second input is the non-white space, which terminates the scan, but left in the buffer (remains unread) for the next scan.

下一次起,最后输入(留在缓冲液中)被认为是<青霉>扫描的输入,以及当前的输入可以作为终止子,正好留在缓冲器等。

Next time onwards, the last input (left in the buffer) is considered as the scanned input , and the current input works as the terminator, just to be left in the buffer and so on.

所以,最后输入( 6 ),实际上从来不读入数组,即仍然是一个单纯的终止的。环比前五个输入考虑。
只是要清楚,从 C11 ,章§7.21.6.2,第(5)的报价重点煤矿

So, the very last input (6), is never actually read into the array, that remains as a mere terminator. The sequential first five inputs are considered. Just to make it clear, quoting from C11, chapter §7.21.6.2, paragraph (5), emphasis mine

的空白字符(S)组成的指令被读取输入的到第一个非空白字符(这仍然未读)执行或直到没有更多的字符可被读出。

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

这篇关于为什么scanf的要求输入两次,只是仅在第一循环迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆