codechaser
V2EX  ›  C

为什么这个输入字母会一直输出一大串 0?

  •  
  •   codechaser · Oct 26, 2018 · 4456 views
    This topic created in 2930 days ago, the information mentioned may be changed or developed.
    #include <stdio.h>
    
    int main(void) {
        int x = 0;
        while (1){
            x = scanf("%d",&x);
            printf("%d",x);
        }
        return 0;
    }
    
    Supplement 1  ·  Oct 26, 2018
    ```c
    #include <stdio.h>

    int main() {
    int x = 0;

    while (1){
    x = scanf("%d",&x);
    setbuf(stdin,NULL);
    printf("%d",x);
    }

    return 0;
    }
    ```没有一直输出 0 了
    18 replies  •  2018-10-26 20:11:53 +08:00
    wevsty
    wevsty
    Oct 26, 2018
    1
    scanf 的返回值并不是输入的内容。
    messyidea
    messyidea
    Oct 26, 2018
    2
    输入字母不应该是 %c 么
    Ginray
    Ginray
    Oct 26, 2018
    3
    一楼正解
    yuikns
    yuikns
    Oct 26, 2018
    4
    https://linux.die.net/man/3/scanf

    These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
    zuoyouTU
    zuoyouTU
    Oct 26, 2018
    6
    稍补充下,等号表达式最后执行
    a516585610
    a516585610
    Oct 26, 2018 via Android
    7
    %d 输入字母会失败,scanf 返回 0 输出当然也是 0
    webdisk
    webdisk
    Oct 26, 2018 via Android
    8
    while (1) 后面是不是少个空格
    aopod
    aopod
    Oct 26, 2018❤️1
    9
    针对一直输出的问题,或许试试清除缓冲区?
    codechaser
    codechaser
    OP
    Oct 26, 2018
    10
    @wevsty 这个我知道啊,输入字母 scanf 返回 0,打印 0 能理解,但是为什么一直在打印 0 啊?求教
    xiaopc
    xiaopc
    Oct 26, 2018 via Android
    11
    @codechaser 因为你 while (1) 了
    codechaser
    codechaser
    OP
    Oct 26, 2018
    12
    @webdisk 这跟空格有啥关系啊😓
    codechaser
    codechaser
    OP
    Oct 26, 2018
    13
    @xiaopc 但是输入数字就能多次输入
    codechaser
    codechaser
    OP
    Oct 26, 2018
    14
    @aopod 谢谢老哥!我在`x=scanf("%d",&x)`后面加了句`setbuf(stdin,NULL);`就没有一直输出了!感谢!能讲解下原因吗
    xiaopc
    xiaopc
    Oct 26, 2018 via Android❤️1
    15
    @codechaser 对对,是缓存区的问题。
    scanf 没从 stdin 读到对应数据不会清除缓冲区。
    codechaser
    codechaser
    OP
    Oct 26, 2018
    16
    @xiaopc 是的,scanf 在这里会跳过非数字,把字母一直留在缓冲区,所以每次读入的都是之前输入的字母,也就一直打印 0 了
    jimchen9999
    jimchen9999
    Oct 26, 2018
    17
    the issue lies with the buffer in C
    webdisk
    webdisk
    Oct 26, 2018
    18
    @codechaser 没关系,但是不符合编码规则我就难受
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4986 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 07:23 · PVG 15:23 · LAX 23:23 · JFK 02:23
    ♥ Do have faith in what you're doing.