且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

验证 do-while 循环中的输入类型 C

更新时间:2021-11-17 03:03:07

问题在于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

'希望有帮助!