1

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

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

但是如果我插入一个字符,它会以一个无限循环开始,但我会简单地验证 int 值。

4

2 回答 2

2

使用的返回值scanf来实现这一点:

int myInt;
while (scanf("%d", &myInt) != 1) {
    // scanf failed to extract int from the standard input
}
// TODO: integer successfully retrieved ...
于 2013-10-18T18:50:25.423 回答
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 中的交互式输入可以很简单,也可以很健壮你不能两者兼得。

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

于 2013-10-18T19:44:56.673 回答