首页 > 解决方案 > 为什么输入字符时循环会陷入无限循环

问题描述

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

#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;
}

标签: c

解决方案


输入字符时程序会陷入死循环。

当您没有为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 % 

推荐阅读