在 while 循环中, fgets() 以换行符作为输入自行运行

In a while loop, fgets() runs by its self taking in a newline as the input

char theInput[10];
long option;
int innerLoop = 1;
char *dunno;
while(innerLoop == 1){
  printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: ");
  fgets(theInput, sizeof theInput, stdin);
  option = strtol(theInput, &dunno, 10);
  if(option == 1){
    loop = 0;
    innerLoop = 0;
  }else if(option == 2){
    loop = 1;
    outerLoop = 1;
    innerLoop = 0;
    firstLoop = 0;
  }else if(option == 3){
    loop = 1;
    innerLoop = 0;
    outerLoop = 1;
    firstLoop = 1;
  }else{
    printf("\nInvalid input, please try again.\n");
    innerLoop = 1;
  }
}

此代码的结果是,当第一个 运行 时,它打印 "Type '1' to get" 部分,然后是换行符,然后是 "Invalid input, please try again.",而不从命令行获取任何输入。然后它再次打印第一个 printf 语句,然后接受输入并开始工作。它的意思是打印第一条语句然后等待输入。

下面是终端输出。

“输入“1”找零,输入“2”到 select 另一项,或输入“3”添加更多资金: 输入无效,请重试

输入“1”找零,输入“2”到 select 另一项,或输入“3”添加更多资金:“

你能尝试刷新标准输出吗?

如果其他人想要一个工作示例,我已经添加了主要方法:

#include <stdio.h>

int main () {
  int loop = 0;
  int outerLoop = 0;
  int firstLoop = 0;

  char theInput[10];
  long option;
  int innerLoop = 1;
  char *dunno;
  while(innerLoop == 1){
    printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: ");
    fflush(stdout);
    fgets(theInput, sizeof theInput, stdin);
    option = strtol(theInput, &dunno, 10);
    if(option == 1) {
      loop = 0;
      innerLoop = 0;
    }else if(option == 2){
      loop = 1;
      outerLoop = 1;
      innerLoop = 0;
      firstLoop = 0;
    }else if(option == 3){
      loop = 1;
      innerLoop = 0;
      outerLoop = 1;
      firstLoop = 1;
    }else{
      printf("\nInvalid input, please try again.\n");
      innerLoop = 1;
    }
  }
}

在修改您的源代码之前,您可以单独尝试运行这个例子,看看您是否有预期的结果?