整数的scanf获取字符时如何处理异常 [英] How to handle exception when scanf of integer gets a character

查看:46
本文介绍了整数的scanf获取字符时如何处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当输入是一个字符时,下面的简单程序将给出一个无限循环,尽管它的意思是从一个数字中分辨出一个字符.如何使用scanf的返回值测试scanf是否得到一个应该是数字的字符?

The following simple program would give an endless loop when the input is a character, though it meant to tell a character from a digit. How to test if scanf gets a character when it is supposed to be a digit using the return value of 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;
}

推荐答案

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

As Joachim pointed in his answer that the character doesn't consumed by scanf here and lives in the buffer, on next iteration scanf again read the same character and again leave it to the buffer and so on. This results in infinite loop.

您需要在下一次迭代之前消耗此字符.只需在 return_value = scanf("%d", &n);

You need to consume this character before next iteration. Just place a getchar() after the line return_value = scanf("%d", &n);

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

这篇关于整数的scanf获取字符时如何处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆