这就是为什么我通常建议不要使用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 上的格式。