在对scanf函数和getchar函数混合使用时发现假如把getchar处理的那一段删除的话会出现无限循环的情况?
long get_long(void){ //获取输入的值
long input;
char ch;
while (scanf("%ld",&input) != 1) {
//如果去除下面这个while语句的话会发生无限循环,为什么?
while ((ch = getchar()) != '\n') {
putchar(ch);
}
printf(" is not an integer.\nPlease enter an integer value:");
}
return input;
}
scanf()在没有输入时,返回值为0,所以该条件满足 0!=1, 循环打印printf(" is not an integer.\nPlease enter an integer value:");
因为一旦scanf读入错误,输入缓存中的内容并不会自动清空,需要调用getchar或类似的函数把输入缓存中的内容读走,否则scanf函数会一直读取错误,造成死循环。
你可以加入类似的打印,验证原因:
long get_long(void){ //获取输入的值
long input;
char ch;
printf("please input integer:");
while (scanf("%ld",&input) != 1) {
//如果去除下面这个while语句的话会发生无限循环,为什么?
/*while ((ch = getchar()) != '\n') {
putchar(ch);
}*/
printf("have get:%c\n",getchar());
printf(" is not an integer.\nPlease enter an integer value:");
}
printf("have get %ld",input);
return input;
}