楔子
#include <stdio.h>
int main(int, char**)
{
int a;
while (true)
{
fputs("please input an integer: ", stdout);
scanf("%d", &i);
printf("%d\n", a);
}
return 0;
}
这段代码会首先提示用户输入一个整数,然后等待用户输入(所谓等待
的意思即是当前输入缓冲区数据为空,需要新的输入进来),如果用户输入的是整数,程序会输出该整数,一旦用户输入的不是整数(浮点数或者字母),假设scanf
函数最后一次得到的整数是2,程序会陷入“please input an integer: 2”的死循环。这是因为scanf("%d", &a);
只能接受整数,如果用户输入了字母,则这个字母会留在输入缓冲区
中,因为缓冲中有数据,故scanf
函数不会等待用户输入,直接就去缓冲中读取,可是缓冲中的却是字母,这个字母再次被遗留在缓冲中,如此反复,从而导致不停地输出“please input an integer: 2”。
如果是在windows平台下开发,且不考虑程序的可移植性,可以使用 vs 系列编译器为C标准所做的拓展,也即使用fflush(stdin)
来清空输入缓冲区。