c - 如何在一段时间内重复一个过程直到按下回车?

标签 c while-loop

我需要重复一个过程,我正在使用一段时间。当按下回车键并且我正在使用 if(getchar()) 时,我需要执行另一个过程。问题是 while 在到达 if 时“暂停”,因为它正在检查 getchar() 是否为真。我需要知道如何在不停止检查是否有输入的情况下继续循环。 我正在制作一款游戏,您可以在 1 分钟内猜出尽可能多的名字。所以 while() 的目的是从 60 秒倒计时到 0 秒(清除屏幕并打印新的秒数和您每秒实际猜测的名字)。所以我希望它继续运行 while() 以便计时器继续运行,但如果按下 enter,它只会将猜测的名称更改为新名称并且计时器继续运行。 (我不知道我是否清楚,但就是这个想法)

//program in c

while(//specific condition)
{
  /*- here goes the code for a timer that every second it clears the
    - terminal and prints the next number (in seconds).
    -
    -
    -*/
  if(getchar()) //the current program stops here and keeps running the loop 
                //until enter is pressed
    {
      //second process
    }
}

我希望 while 一直循环直到出现输入。当发生这种情况时,我希望它进入 if,退出 if 并继续循环。

最佳答案

char buffer[100];
while (fgets(buffer, sizeof(buffer), stdin))
{
        if (strlen(buffer) == 1)
        break;   

    if (sscanf(buffer, "%f", &f) == 1)
    {
        total += f;
        printf("Enter another number: ");
    }
}

关于c - 如何在一段时间内重复一个过程直到按下回车?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56420689/

相关文章:

c - 接受二维数组中的多个字符串?

python - 我如何与正在运行的进程通信?

c - 什么时候可以将整数传递给需要无符号的函数,反之亦然

c - 循环遍历数据文件末尾

python - 为什么我看起来有一个无限循环?

c - k&r 中的 getint 模糊定义,其中 ungetch 的奇怪行为

c - 如何在链表中查找重复项?

c - C中语句的含义

c++ - 意外的 while 行为 C++(可能与 IDE 相关)

java - 为什么这个 'if' 语句不会在 while 循环中运行,而 while 循环中也不会发生其他事情?