检查输入程序陷入无限循环

标签 c

我正在尝试创建一个程序,要求输入一些内容并检查它是否为整数。如果它是一个整数,则打印“整数是...”。否则,打印“再试一次”并等待另一个输入。但是,如果您输入一个字符,该程序会打印无限次的“再试一次”。这是源代码:

#include <stdio.h>
#include <stdbool.h>

int main()
{
  int inp;
  bool t = 1;
  printf("type an integer\n");
  while (t) {
    if (scanf("%i", &inp) == 1) { 
      printf("The integer is %i", inp);
      t = 0;
    } else {
      printf("try again");
      scanf("%i", &inp);
    }
  }
}

最佳答案

OP 的代码无法使用有问题的非数字输入。它保留在 stdin 中,用于下一个输入函数。不幸的是,它只是另一个以同样方式失败的 scanf("%i", &inp) - 无限循环。

尝试读取 int 后,读取该行的其余部分。

#include <stdio.h>
#include <stdbool.h>

int main() {
  int inp;
  int scan_count;
  printf("Type an integer\n");
  do {
    scan_count = scanf("%i", &inp); // 1, 0, or EOF

     // consume rest of line
    int ch;
    while ((ch == fgetchar()) != '\n' && ch != EOF) {
      ;
    }

  } while (scan_count == 0); 
  if (scan_count == 1) {  
    printf("The integer is %i\n", inp);
  } else {
    puts("End of file or error");
  }
}

更好的方法是使用 fgets() 读取用户输入行。 Example

关于检查输入程序陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292347/

相关文章:

c - AVX2 中的 8 位移位操作,移入零

c - 结构内部结构

我们可以选择为变量保留多少位?

c++ - 结构前缀的布局

c - C 中的 void display_board(enum cell_contents board[][BOARDWIDTH])

C套接字重定向

c - 尝试将 CSV 数据解析为 C 中的结构时出错

c - 从缓冲区和位置绘制像素 (glDrawPixels)

c - 使用 CAS(Compare And Swap)时,如何确保旧值确实是旧值?

c - Swift/C 互操作,Swift 中的结构数据更改未在 C 中更新