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

2018-10-26 14:19:11 +08:00
 codechaser
#include <stdio.h>

int main(void) {
    int x = 0;
    while (1){
        x = scanf("%d",&x);
        printf("%d",x);
    }
    return 0;
}
3112 次点击
所在节点    C
18 条回复
wevsty
2018-10-26 14:24:07 +08:00
scanf 的返回值并不是输入的内容。
messyidea
2018-10-26 14:24:21 +08:00
输入字母不应该是 %c 么
Ginray
2018-10-26 14:26:33 +08:00
一楼正解
yuikns
2018-10-26 14:28:10 +08:00
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.
xxgirl2
2018-10-26 14:45:37 +08:00
zuoyouTU
2018-10-26 16:56:43 +08:00
稍补充下,等号表达式最后执行
a516585610
2018-10-26 18:33:09 +08:00
%d 输入字母会失败,scanf 返回 0 输出当然也是 0
webdisk
2018-10-26 18:35:36 +08:00
while (1) 后面是不是少个空格
aopod
2018-10-26 18:45:14 +08:00
针对一直输出的问题,或许试试清除缓冲区?
codechaser
2018-10-26 19:12:26 +08:00
@wevsty 这个我知道啊,输入字母 scanf 返回 0,打印 0 能理解,但是为什么一直在打印 0 啊?求教
xiaopc
2018-10-26 19:14:40 +08:00
@codechaser 因为你 while (1) 了
codechaser
2018-10-26 19:16:55 +08:00
@webdisk 这跟空格有啥关系啊😓
codechaser
2018-10-26 19:18:09 +08:00
@xiaopc 但是输入数字就能多次输入
codechaser
2018-10-26 19:22:53 +08:00
@aopod 谢谢老哥!我在`x=scanf("%d",&x)`后面加了句`setbuf(stdin,NULL);`就没有一直输出了!感谢!能讲解下原因吗
xiaopc
2018-10-26 19:25:50 +08:00
@codechaser 对对,是缓存区的问题。
scanf 没从 stdin 读到对应数据不会清除缓冲区。
codechaser
2018-10-26 19:36:45 +08:00
@xiaopc 是的,scanf 在这里会跳过非数字,把字母一直留在缓冲区,所以每次读入的都是之前输入的字母,也就一直打印 0 了
jimchen9999
2018-10-26 19:38:59 +08:00
the issue lies with the buffer in C
webdisk
2018-10-26 20:11:53 +08:00
@codechaser 没关系,但是不符合编码规则我就难受

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/501403

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX