This is why I usually advise against using scanf
for interactive input; for the amount of work required to make it really bulletproof, you might as well use fgets()
and use strtod
or strtol
to convert to numeric types.
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
}
Interactive input in C can be simple xor it can be robust. You can't have both.
And somebody really needs to fix formatting on IE.