整数的scanf获取字符时如何处理异常

Geo*_*rge 3 c scanf

当输入是一个字符时,以下简单程序将给出一个无限循环,尽管这意味着从数字中分辨出一个字符。如何scanf使用返回值测试是否假设某个字符是数字scanf

#include <stdio.h>

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;
}
Run Code Online (Sandbox Code Playgroud)

hac*_*cks 5

正如Joachim在他的回答中指出的那样,该字符scanf在这里没有被占用,而是生活在缓冲区中,在下一次迭代时,它scanf再次读取相同的字符,并将其留在缓冲区中,依此类推。这导致无限循环。

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

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