错误输入后如何刷新缓冲区

时间:2013-10-18 18:48:14

标签: c validation io int scanf

我必须在输入中获取一个int,以验证它我写道:

 do {
    scanf("%d", &myInt);
    if (myInt >= 2147483648 || myInt <= -2147483648)
        printf("I need an integer between -2147483647 and 2147483647: ");
} while (myInt >= 2147483648 || myInt <= -2147483648);

但是如果我插入一个char,它会以无限循环开始,但我只是验证int值。

2 个答案:

答案 0 :(得分:2)

使用scanf的返回值来实现此目的:

int myInt;
while (scanf("%d", &myInt) != 1) {
    // scanf failed to extract int from the standard input
}
// TODO: integer successfully retrieved ...

答案 1 :(得分:0)

这就是为什么我通常建议反对使用scanf进行交互式输入;对于使其真正具有防弹性所需的工作量,您也可以使用fgets()并使用strtodstrtol转换为数字类型。

char inbuf[MAX_INPUT_LENGTH];
...
if ( fgets( inbuf, sizeof inbuf, stdin ))
{
  char *newline = strchr( inbuf, '\n' );
  if ( !newline )
  {
    /**
     * no newline means that the input is too large for the
     * input buffer; discard what we've read so far, and
     * read and discard anything that's left until we see
     * the newline character
     */
    while ( !newline )
      if ( fgets( inbuf, sizeof inbuf, stdin ))
        newline = strchr( inbuf, '\n' );
  }
  else
  {
    /**
     * Zero out the newline character and convert to the target
     * data type using strtol.  The chk parameter will point
     * to the first character that isn't part of a valid integer
     * string; if it's whitespace or 0, then the input is good.
     */
    newline = 0;

    char *chk;
    int tmp = strtol( inbuf, &chk, 10 );
    if ( isspace( *chk ) || *chk == 0 )
    {
      myInt = tmp;
    }
    else
    {
      printf( "%s is not a valid integer!\n", inbuf );
    }
  }
}
else
{
  // error reading from standard input
}

C中的交互式输入可以很简单 xor 它可以很健壮。你不能两者兼得。

有人真的需要修复IE上的格式。