V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
codechaser
V2EX  ›  C

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

  •  
  •   codechaser · Oct 26, 2018 · 3866 views
    This topic created in 2748 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
        1
    wevsty  
       Oct 26, 2018
    scanf 的返回值并不是输入的内容。
    messyidea
        2
    messyidea  
       Oct 26, 2018
    输入字母不应该是 %c 么
    Ginray
        3
    Ginray  
       Oct 26, 2018
    一楼正解
    yuikns
        4
    yuikns  
       Oct 26, 2018
    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
        6
    zuoyouTU  
       Oct 26, 2018
    稍补充下,等号表达式最后执行
    a516585610
        7
    a516585610  
       Oct 26, 2018 via Android
    %d 输入字母会失败,scanf 返回 0 输出当然也是 0
    webdisk
        8
    webdisk  
       Oct 26, 2018 via Android
    while (1) 后面是不是少个空格
    aopod
        9
    aopod  
       Oct 26, 2018   ❤️ 1
    针对一直输出的问题,或许试试清除缓冲区?
    codechaser
        10
    codechaser  
    OP
       Oct 26, 2018
    @wevsty 这个我知道啊,输入字母 scanf 返回 0,打印 0 能理解,但是为什么一直在打印 0 啊?求教
    xiaopc
        11
    xiaopc  
       Oct 26, 2018 via Android
    @codechaser 因为你 while (1) 了
    codechaser
        12
    codechaser  
    OP
       Oct 26, 2018
    @webdisk 这跟空格有啥关系啊😓
    codechaser
        13
    codechaser  
    OP
       Oct 26, 2018
    @xiaopc 但是输入数字就能多次输入
    codechaser
        14
    codechaser  
    OP
       Oct 26, 2018
    @aopod 谢谢老哥!我在`x=scanf("%d",&x)`后面加了句`setbuf(stdin,NULL);`就没有一直输出了!感谢!能讲解下原因吗
    xiaopc
        15
    xiaopc  
       Oct 26, 2018 via Android   ❤️ 1
    @codechaser 对对,是缓存区的问题。
    scanf 没从 stdin 读到对应数据不会清除缓冲区。
    codechaser
        16
    codechaser  
    OP
       Oct 26, 2018
    @xiaopc 是的,scanf 在这里会跳过非数字,把字母一直留在缓冲区,所以每次读入的都是之前输入的字母,也就一直打印 0 了
    jimchen9999
        17
    jimchen9999  
       Oct 26, 2018
    the issue lies with the buffer in C
    webdisk
        18
    webdisk  
       Oct 26, 2018
    @codechaser 没关系,但是不符合编码规则我就难受
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   815 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 19:19 · PVG 03:19 · LAX 12:19 · JFK 15:19
    ♥ Do have faith in what you're doing.