当整数的scanf获得一个字符时如何处理exception

当输入是一个字符时,下面的简单程序会给出无限循环,尽管它意味着从数字中告诉一个字符。 如何使用scanf的返回值测试scanf是否应该是一个数字?

 #include  int main() { int n; int return_value = 0; while (!return_value) { printf("Input a digit:"); return_value = scanf("%d", &n); } printf("Your input is %d\n", n); return 0; } 

正如Joachim在他的回答中指出的那样,字符不会被scanf消耗scanf在于缓冲区中,在下一次迭代时, scanf再次读取相同的字符并再次将其留给缓冲区,依此类推。 这导致无限循环。

您需要在下一次迭代之前使用此字符。 只需在return_value = scanf("%d", &n);行之后放置一个getchar() return_value = scanf("%d", &n);

 return_value = scanf("%d", &n); while(getchar() != '\n'); // will consume the charater 

你得到一个无限循环,因为scanf不消耗字符,所以字符永远不会离开输入缓冲区。

你可以通过读取一行例如fgets来解决它,然后在线上使用sscanf

添加第二个(嵌套循环)循环,在尝试使用另一个scanf读取之前清除输入缓冲区。

我没有在很长一段时间内完成,但它是这样的:#include

 int main() { int n; int return_value = 0; while (!return_value) { printf("Input a digit:"); return_value = scanf("%d", &n); // this loop will "eat" every character that's left in input buffer while(getchar() !='\n') { continue; } } printf("Your input is %d\n", n); return 0; } 

基本上,任何在失败后清除输入缓冲区的函数/方法都将以相同的方式工作。 选择一个你最喜欢的。

您应该使用TheDubleM的建议,并检查buffer是否为数字,如果是,请使用atoi。 在我下面的内容中,您不会将8f8检测为输入错误但只读取8。

 #include  int main() { int n; int return_value = 0; char buffer[1024]; while (!return_value) { printf("Input a digit:"); scanf("%1024s", buffer); return_value = sscanf(buffer, "%d", &n); } printf("Your input is %d\n", n); return 0; }