为什么 while 会无限循环 运行 而不是等待来自 fgets() 的更多输入?

Why does a while loop run infinitely instead of waiting for more input from fgets()?

天哪,这该死的东西难倒我了。我想创建一个循环来验证用户是否输入了 int(而不是其他数据类型)。为此,我使用 fgets() 获取用户输入的第一个字符,然后检查该字符是否为数字(这是我任务中要破解的代码的最少部分)。

char input[2];

int main(){
  printf("Please enter the minimum value the random number can be: ");
  fgets(input, sizeof(input), stdin);
  printf("%c", input[0]);
  if(!isdigit(input[0])){
    int escape = 0;
    while(escape == 0)
      printf("Try again: ");
      fgets(input, sizeof(input), stdin); //This will now overwrite whatever was in 'input'
      if (isdigit(input[0])) //Will keep looping back to the fgets(), asking for new input each time until you enter a number.
        escape = 1;
      flushInpt();
  }

在上面的代码中(假设所有正确的库都#included),它应该要求输入(它确实)然后检查该输入的第一个字符是否是一个数字(它所做的),如果它不是一个数字,它应该进入一个while循环,在那里它打印"Try again: "和一个新的fgets()等待用户输入新的输入。它停留在 while 循环中,直到他们输入一个数字作为第一个字符,此时它跳出循环(这是它不做的部分 )。

但是每当我第一次输入一个非数字时,它都会按预期进入 while 循环,然后无限地一遍又一遍地打印 "Try again: " 而不会在 getsf() 处停止语句等待新的输入?我的问题是为什么会无限循环?


我也已验证 flushInpt() 函数不是罪魁祸首,因为无论该调用是否在循环中都会出现问题。如果您想知道,flushInpt 只是一个基本的循环函数,它遍历输入缓冲区并删除可能存在的任何内容。

char ch;

void flushInpt(){
  while ((ch = getchar()) != '\n' && ch != EOF)
  continue;
}

您缺少大括号:

while(escape == 0)
{   //<--
  printf("Try again: ");
  fgets(input, sizeof(input), stdin); //This will now overwrite whatever was in 'input'
  if (isdigit(input[0])) //Will keep looping back to the fgets(), asking for new input each time until you enter a number.
    escape = 1;
  flushInpt();
}   //<--

我猜这个块是你的 while 循环。