验证 do-while 循环中的输入类型 C [英] Validate the type of input in a do-while loop C

查看:33
本文介绍了验证 do-while 循环中的输入类型 C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要确保输入是整数,如下所示:

Basically, I need to ensure that input is an integer, like so:

do {
    printf("Enter > ");
    scanf("%d", &integer);
} while (/* user entered a char instead of an int */);

我尝试了各种方法,但是当我尝试输入 char 时,总是以运行时错误或无限循环告终.我已经知道 fflush(stdin) 是一个未定义的行为,最好不要将它包含在我的代码中以防止任何错误加上 它在 VS2015 中不再有效由于某些原因.

I have tried various methods, but it always end up with run-time error or infinite loop when I tried to enter a char. I have knew that fflush(stdin) is an undefined behavior, which is better not to involve it in my code in order to prevent any error plus it no longer works in VS2015 due to some reasons.

下面的代码是我试过的方法:

The codes below are the method that I have tried:

typedef enum {false, true} bool;
int ipt;
char c;
bool wrong_ipt;

do {
    c = '';
    printf("Enter > ");
    scanf("%d%c", &ipt, &c); //infinite loop occurs while a char has been entered
} while (c != '
');

do {
    c = '';
    printf("Enter > ");
} while (scanf("%d", &ipt) != EOF);

do {
    wrong_ipt = false;
    do {
        ipt = NULL;
        printf("Enter > ");
        scanf("%d", &ipt);
        if (ipt == NULL) {
            wrong_ipt = true;
            break;
        }
    } while (ipt == NULL);
} while (wrong_ipt);

除了 fflush(stdin) 之外,还有什么可以用来防止用户在 C 中输入 char 时的无限循环?

Is there anyway other than fflush(stdin) which can be used to prevent the infinite loop when user entered a char in C?

谢谢

推荐答案

问题在于scanf()"可以在输入缓冲区中留下未读数据.因此,无限循环".

The problem is that "scanf()" can leave unread data in your input buffer. Hence the "infinite loop".

另一个问题是您应该验证 scanf() 的返回值.如果您期望一个整数值……并且 scanf 返回0";项目读取...然后您就知道出了点问题.

Another issue is that you should validate the return value from scanf(). If you expect one integer value ... and scanf returns "0" items read ... then you know something went wrong.

这是一个例子:

#include <stdio.h>

void discard_junk () 
{
  int c;
  while((c = getchar()) != '
' && c != EOF)
    ;
}

int main (int argc, char *argv[])
{
  int integer, i;
  do {
      printf("Enter > ");
      i = scanf("%d", &integer);
      if (i == 1) {
        printf ("Good value: %d
", integer);
      }
      else {
        printf ("BAD VALUE, i=%i!
", i);
        discard_junk ();
      }
   } while (i != 1);

  return 0;
}

示例输出:

Enter > A
BAD VALUE, i=0!
Enter > B
BAD VALUE, i=0!
Enter > 1
Good value: 1

'希望有帮助!

这篇关于验证 do-while 循环中的输入类型 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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