【问题标题】:In a while loop, fgets() runs by its self taking in a newline as the input在 while 循环中, fgets() 自行运行,以换行符作为输入
【发布时间】:2017-02-11 21:47:02
【问题描述】:
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”部分,然后是换行符,然后是“无效输入,请重试”。无需从命令行获取任何输入。然后它再次打印第一个 printf 语句,然后接受输入并工作。它意味着打印第一条语句然后等待输入。

下面是终端输出。

“输入‘1’获取零钱,‘2’选择另一个项目,或‘3’添加更多资金: 输入无效,请重试。

输入“1”获取零钱,输入“2”选择其他项目,或输入“3”添加更多资金:"

【问题讨论】:

  • 您发布的代码不会打印您提到的内容(例如,“Type 'C' to get your change”部分)。错误很可能出在您未发布的代码部分中..
  • 感谢您的回复。这是我在发布时更新代码的错误 - 我将其从 C、N 和 A 更改为 1、2、3,因为我认为处理整数可能更容易。我已经更新了帖子,所以一切都和我电脑上当前运行的一样。
  • 之前未发布的代码使用了在stdin 中留下'\n' 的输入函数。
  • 它可以在我的机器上运行,所以我猜有人编辑了您的帖子并意外修复了您遇到的问题?
  • 我怀疑在此代码运行之前调用了 scanf。这就是为什么调试问题应该始终包含minimal, complete, and verifiable example

标签: c while-loop fgets strtol


【解决方案1】:

你可以尝试刷新标准输出吗?

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

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

在调整你的源代码之前,你能不能试着在隔离中运行这个例子,看看你是否有预期的结果?

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多