これが、通常、対話型入力に使用しないようにアドバイスする理由です。scanf
それを本当に防弾にするために必要な作業量については、使用fgets()
して使用するstrtod
かstrtol
、数値型に変換することもできます。
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 のフォーマットを修正する必要があります。