我正在使用什么scanf() returns when it gets what is expects or when it doesn't. What happens is it gets stuck in the
while() '循环
据我所知,如果test = scanf("%d", &testNum);
接收到数字,则返回1,如果没有,则返回0。
#include<stdio.h>
int main(void) {
while (1) {
int testNum = 0;
int test;
printf("enter input");
test = scanf("%d", &testNum);
printf("%d", test);
if (test == 0) {
printf("please enter a number");
testNum = 0;
}
else {
printf("%d", testNum);
}
}
return(0);
}
这里的问题是,当遇到无效的输入(例如,一个字符)时,不正确的输入不会被使用,它保留在输入缓冲区中。
因此,在下一个循环中,scanf()
再次读取相同的无效输入。
您需要在识别错误输入后清理缓冲区。一个非常简单的方法是,
if (test == 0) {
printf("please enter a number");
while (getchar() != 'n'); // clear the input buffer off invalid input
testNum = 0;
}
也就是说,要么初始化test
,要么删除printf("%d", test);
,因为test
是一个自动变量,除非显式初始化,否则包含不确定的值。尝试使用可能会调用未定义行为。
也就是说,仅仅是挑剔的, return
不是一个函数,不要让它看起来像一个函数。这是一个声明,所以return 0;
更抚慰眼睛,更少令人困惑,无论如何。