【问题标题】:How to flush buffer after wrong input [duplicate]输入错误后如何刷新缓冲区[重复]
【发布时间】:2013-10-18 18:48:14
【问题描述】:

我必须在输入中获得一个 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 值。

【问题讨论】:

  • 如果这些数字是 INT_MAX 和 INT_MIN,那 if 语句不会永远为真吗?
  • @CharlieBurns 我会这么认为。除非在 64 位 int 架构上对 32 位限制进行硬编码(即 OP 使用 64 位 int 但需要 32 位限制),否则它似乎有点毫无意义。
  • @WhozCraig,我在想 。他有 = 所以 INT_MIN 和 INT_MAX 是正确的。尽管如此,我怀疑这就是他的想法。

标签: c validation io int scanf


【解决方案1】:

使用scanf的返回值来实现:

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

【讨论】:

  • 会不会正好相反? while (scanf("%d", &amp;myInt) != 1) { //TODO: scanf failed to retrieve integer ... }
  • @fvdalcin:好点。
  • 唯一的问题是,如果用户输入类似 12w3 的内容,12 将被转换并分配给 myIntscanf 将返回 1,留下 w3在输入流中破坏下一次读取。
【解决方案2】:

这就是为什么我通常建议反对使用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 中的交互式输入可以很简单 xor 它可以很健壮。你不能两者兼得。

有人真的需要修复 IE 上的格式。

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2020-10-05
    • 2010-12-25
    • 2012-03-27
    相关资源
    最近更新 更多