首页 > 一个for循环中scanf的问题

一个for循环中scanf的问题

int main(void) {
    int a[5] = {0};
    for (int i = 0; i<5; i++) {
        scanf("%d",&a[i]);
        printf("%d",a[i]);
    }
    return 0;
}

若输入“1 2 3 4 5”,按scanf的语法这么输入只能赋给a[0],后面的“2 3 4 5”都会被忽略掉,printf也只会打印一个“1”出来。
可是实际情况是数组全被赋值了,运行结果是“12345”。
怎么会这样呢??求高手指教。


为什么只能赋给&a[0]呢?

scanf就是从缓冲区里拿东西出来,scanf能拿到哪里就拿到哪里


#include <stdio.h>
int main(void) {
    int a[5] = {0};
    int i = 0;
    int n = 0;
    for (i; i<5; i++) {
        scanf("%d",&a[i]);
        printf("%d",a[i]);
    }
    for(n;n<5;n++){
        printf("\n");
        printf("%d",a[n]);
    }
    return 0;
}

你跑下这个


输入“1 2 3 4 5”, 数据存入缓冲区;
for循环实际是从缓冲区拿数据, 顺次拿到 1 2 3 4 5, 所以全部打出来1 2 3 4 5

for (int i = 0; i<5; i++) {
        scanf("%d",&a[i]);
        printf("%d",a[i]);
    }

scanf 吃了 1 之后,printf 输出 1, 循环继续,scanf 吃 2 ... 就这样一直往下走。
scanf 吃到东西就往下走

>gdb /tmp/test
GNU gdb (GDB) 7.6.1
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "mingw32".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from F:\tmp\test.exe...done.
(gdb) l
1       #include <stdio.h>
2
3
4       int main(int argc, char **argv){
5         int a[5] = {0};
6         int i;
7         for (i = 0; i<5; i++) {
8           scanf("%d", &a[i]);
9           printf("%d", a[i]);
10        }
(gdb) b 4
Breakpoint 1 at 0x4013ee: file test.c, line 4.
(gdb) r
Starting program: /tmp/test.exe
[New Thread 980.0x11ec]

Breakpoint 1, main (argc=1, argv=0x7a0de0) at test.c:5
5         int a[5] = {0};
(gdb) n
7         for (i = 0; i<5; i++) {
(gdb) n
8           scanf("%d", &a[i]);
(gdb) n
1 2 3 4 5
[New Thread 980.0x1404]
9           printf("%d", a[i]);
(gdb) n
7         for (i = 0; i<5; i++) {
(gdb) n
8           scanf("%d", &a[i]);
(gdb) p a[0]
$1 = 1
(gdb) n
9           printf("%d", a[i]);
(gdb) n
7         for (i = 0; i<5; i++) {
(gdb) n
8           scanf("%d", &a[i]);
(gdb) n
9           printf("%d", a[i]);
(gdb) p a[1]
$2 = 2

&a[i] ,i跟着循环变啊!这有什么问题。

【热门文章】
【热门文章】