为什么输入字符时循环会陷入无限循环

时间:2019-03-18 10:18:23

标签: c

这是错误的代码。 错误的问题之一是,键入字符时程序将陷入无限循环。 请忽略代码中存在的其他错误,仅关注字符导致无限循环的问题。

#include <stdio.h>
int main()
{
  int x1, x2;
  do{
    printf("Input x1, x2:");
    scanf("%d,%d", &x1, &x2);
  }while (x1 * x2 > 0);
  printf("x1=%d,x2=%d\n", x1, x2);
  return 0;
}

1 个答案:

答案 0 :(得分:1)

  

键入字符时,程序将陷入无限循环。

如果您没有为scanf %d输入有效的数字,则不会删除错误的输入,因此,如果您什么也不做,则会在下一个scanf %d再次得到它。

提案:

#include <stdio.h>

int main()
{
  int x1, x2;
  do{
    printf("Input x1, x2:");

    if (scanf("%d,%d", &x1, &x2) != 2) {
      char * lineptr = NULL;
      size_t n = 0;
      ssize_t r = getline(&lineptr, &n, stdin); /* flush input */

      if (r == -1)
        /* EOF */
        return -1;

      free(lineptr);
    }
  } while (x1 * x2 > 0);
  printf("x1=%d,x2=%d\n", x1, x2);
  return 0;
}

编译和执行:

/tmp % gcc -pedantic -Wextra c.c
/tmp % ./a.out
Input x1, x2:1,2
Input x1, x2:a
Input x1, x2:1,a
Input x1, x2:1 2
Input x1, x2:0,1
x1=0,x2=1

(编辑)

如果您只是想在发生错误时停止循环:

#include <stdio.h>

int main()
{
  int x1, x2;
  int ok = 1;

  do{
    printf("Input x1, x2:");

    if (scanf("%d,%d", &x1, &x2) != 2) {
      ok = 0;
      break;
    }
  } while ((x1 * x2) > 0);

  if (ok)
    printf("x1=%d,x2=%d\n", x1, x2);

  return 0;
}

或完成所有错误执行

#include <stdio.h>

int main()
{
  int x1, x2;

  do{
    printf("Input x1, x2:");

    if (scanf("%d,%d", &x1, &x2) != 2)
      return 0;
  } while ((x1 * x2) > 0);

  printf("x1=%d,x2=%d\n", x1, x2);

  return 0;
}

编译和执行:

/tmp % gcc -pedantic -Wextra c.c
/tmp % ./a.out
Input x1, x2:1,2
Input x1, x2:1,0
x1=1,x2=0
/tmp % ./a.out
Input x1, x2:1,,
/tmp %