今天想写一个简单的ascii码转换程序,确在输入这一块出现了问题。
在上面的图片中,在功能选择那我敲了个2然后回车就直接跳过了代码里switch里面case 2的输入,打印出了回车的ascii码,有大神解答一下吗!?
输入流是行缓冲的,可以试下在读取字符之前用fflush(stdin)清空输入缓冲
加上ffush(stdin)也不行,可能是我不会用,没试过这个
@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
@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: emmmm
setbuf(stdin,0)是可以的,谢谢啦!
估计是Enter=0xd,0xa ,scanf %d 时 检查到 '2', 0xd,就开始进入switch,再次 scanf %c 时,就收到0xa了
按楼上的方法,scanf前先清空