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);

しかし、char を挿入すると、無限ループから始まりますが、単に 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 に答える