C 输入错误后如何刷新缓冲区

C 输入错误后如何刷新缓冲区,c,validation,io,int,scanf,C,Validation,Io,Int,Scanf,我必须在输入中得到一个int,为了验证它,我写了: do { scanf("%d", &myInt); if (myInt >= 2147483648 || myInt <= -2147483648) printf("I need an integer between -2147483647 and 2147483647: "); } while (myInt >= 2147483648 || myInt <= -21474836

我必须在输入中得到一个int,为了验证它,我写了:

 do {
    scanf("%d", &myInt);
    if (myInt >= 2147483648 || myInt <= -2147483648)
        printf("I need an integer between -2147483647 and 2147483647: ");
} while (myInt >= 2147483648 || myInt <= -2147483648);
do{
scanf(“%d”、&myInt);
如果(myInt>=2147483648 | | myInt=2147483648 | | myInt使用的返回值来实现此目的:

int myInt;
while (scanf("%d", &myInt) != 1) {
    // scanf failed to extract int from the standard input
}
// TODO: integer successfully retrieved ...

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

如果这些数字是INT\u MAX和INT\u MIN,那么If语句不是永远都是真的吗?@CharlieBurns我想是的。除非这些是在64位
INT
架构上硬编码的32位限制(即OP使用64位
INT
但需要32位限制),这似乎有点毫无意义。@WhozCraig,我在想。他有=所以INT_MIN和INT_MAX也是如此。尽管如此,我怀疑他是这么想的。不是相反吗?
while(scanf(“%d”,&myInt)!=1){//TODO:scanf无法检索整数…}
@fvdacin:这一点很好。唯一的问题是,如果用户输入类似于
12w3
的内容,
12
将被转换并分配给
myInt
,而
scanf
将返回1,将
w3
留在输入流中,以干扰下一次读取。