首页 新闻 会员 周边

C语言的scanf输入bug???

0
[已解决问题] 解决于 2019-10-28 17:04

今天想写一个简单的ascii码转换程序,确在输入这一块出现了问题。


在上面的图片中,在功能选择那我敲了个2然后回车就直接跳过了代码里switch里面case 2的输入,打印出了回车的ascii码,有大神解答一下吗!?

Ameng12138的主页 Ameng12138 | 菜鸟二级 | 园豆:204
提问于:2019-10-22 17:22
< >
分享
最佳答案
0

输入流是行缓冲的,可以试下在读取字符之前用fflush(stdin)清空输入缓冲

奖励园豆:5
jakio6 | 小虾三级 |园豆:1318 | 2019-10-23 10:40

加上ffush(stdin)也不行,可能是我不会用,没试过这个

Ameng12138 | 园豆:204 (菜鸟二级) | 2019-10-23 22:59

@Ameng12138: 我试了下, 好像是不行..但是去除输入缓冲和手动读取换行是可行的

✔︎ tmp cat test.c
#include <stdio.h>
int main(int argc, char *argv[])
{
    int i;
    char c;
    printf("input int:");
    scanf("%d",&i);
    printf("input char:");
    setbuf(stdin,0);
    /* while(fgetc(stdin) != '\n'); */
    scanf("%c",&c);
    printf("c = %d\n", c);
    return 0;
}
✔︎ tmp tcc -run test.c
input int:123
input char:a
c = 97
✔︎ tmp 
✔︎ tmp 
jakio6 | 园豆:1318 (小虾三级) | 2019-10-24 00:10

@Ameng12138: fflush只定义了刷新输出流..🙈

Synopsis
         #include <stdio.h>
         int fflush(FILE *stream);

Description
If stream points to an output stream or an update stream in which the most recent operation was output, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above.
jakio6 | 园豆:1318 (小虾三级) | 2019-10-24 00:31

@jakio6: emmmm
setbuf(stdin,0)是可以的,谢谢啦!

Ameng12138 | 园豆:204 (菜鸟二级) | 2019-10-24 10:22
其他回答(1)
0

估计是Enter=0xd,0xa ,scanf %d 时 检查到 '2', 0xd,就开始进入switch,再次 scanf %c 时,就收到0xa了
按楼上的方法,scanf前先清空

pencile | 园豆:845 (小虾三级) | 2019-10-23 21:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册