清空键盘缓冲区

遇到的问题:

题目:3、接受用户从键盘上输入两个单精度浮点数,然后输出他们(保留两位整数))

结果输入的浮点数保留了两位整数 但是剩下之滞留在缓冲区 导致第二个浮点数无法准确输入输出


解决方法: 

windows下用 fflush(stdin);/*清空缓冲区,也可以使用rewind(stdin);*/

Linux OSX下用 setbuf(stdin,NULL);/*清空缓冲区*/

举个: windows系统

/*

* 本程序只适用于 Windows 系统,测试平台:

* Windows XP,Microsoft Visual C++ 6.0 SP6

*/

#include

intmain()

{

charch1;

charch2;

scanf("%c",&ch1);

printf("ch1 = %d",ch1);

fflush(stdin);/*清空缓冲区,也可以使用rewind(stdin);*/

scanf("%c",&ch2);

printf("ch2 = %d",ch2);

return0;

}


: Linux系统 OSX系统

/*

* 本程序适用于 Windows 和 Linux 系统,

* 测试环境:

* Windows XP,Microsoft Visual C++ 6.0 SP6

* Ubuntu Linux 8.04, NetBeans IDE 6.7

*/

#include

intmain()

{

charch1;

charch2;

scanf("%c",&ch1);

printf("ch1 = %d",ch1);

setbuf(stdin,NULL);/*清空缓冲区*/

scanf("%c",&ch2);

printf("ch2 = %d",ch2);

return0;

}

你可能感兴趣的:(清空键盘缓冲区)