c - 忽略 while 循环中的第二次运行,C

标签 c

当我尝试第二次运行此循环时,它会打印“输入一个句子”,但会跳转 gets 部分。并立即询问答案以再次运行循环。我可以使用 scanf 如果问题没有出现,我将需要空白。

程序看起来像。

输入一句话:你

再来一次?是/否:是

不错的选择!

输入一个句子:

再来一次?是/否:

int main(void){
  char user_input[20];
  int boolean = 0;
  char val[2];

  do{
      printf("Enter a sentence: ");
      gets(user_input);

      printf("%s\n", user_input);

      printf("One more time? y/n: ");
      scanf("%c", &val[0]);

      if(val[0] == 'y'){
        boolean = 1;
        printf("Good choice!\n");
      }else if(val[0] == 'n'){
        printf("You are really quiting?\n");
        boolean = 0;
      }

  }while(boolean);
  return 0;
}

最佳答案

那是因为你的标准输入缓冲区中仍然有换行符,因此“gets”需要
该换行符作为其输入,您没有机会输入您的换行符。
在 scanf 之后使用 getchar() 来读取换行符,例如:

scanf("%c", &val[0]);
getchar();

或者您可以在 scanf 函数内进行一些调整:

scanf("\n%c", &val[0]); // insert a newline character in the beginning.

关于c - 忽略 while 循环中的第二次运行,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26023494/

相关文章:

c - 重定向标准输出,不理解行为

c - 是否可以访问LR、PC等CPU寄存器

c - 未知 "for"语句 (C)

C 获取范围内的奇数并将其存储在 int 数组中

从命名管道并发选择

c - 内核模块中的 Stackoverflow

c++ - 为什么我可以使用比分配的内存更多的内存?

c - 有没有适合替代C宏的推荐代码生成方式?

c - 运行时错误: Structure for student details in C

c - C 标准的哪一部分允许此代码编译?