为什么在循环内部,带有%d的scanf()不会等待用户输入,以防它先前收到无效输入?

我正在使用scanf() returns when it gets what is expects or when it doesn't. What happens is it gets stuck in the 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 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不是一个function,不要让它看起来像一个。 这是一个问题,所以return 0; 无论如何,对眼睛来说更舒缓,更不用说混乱了。