通过实时按键停止循环

Stop a loop by pressing a key in real-time

本文关键字:循环 实时      更新时间:2023-10-16

我写了一个简单的计时器。通过按"s"(不按回车键提交),计时器(for循环)将启动。这是一个永无止境的循环。我想在用户按下"s"后立即停止它,就像我启动它的方式一样。一旦按"s"(不按回车键提交),循环应该停止。怎么办?

#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
int main()
{
    char ch;
    int m=0,h=0;
    if ((ch = _getch()) == 's')
        for (int i=0;;i++)
        {
            cout << "h   m   s" << endl;
            cout << h << "   " << m << "   " << i;
            system("CLS");
            if (i==60) {i=0;m+=1;}
            if (m==60) {m=0;h+=1;}
            if (h==24) {h=0;}
        }
    return 0;
}

有一个单独的volatile变量,用作退出循环的条件。

在单独的线程上(侦听用户输入并同时保持循环运行的唯一方法)在用户按 "s" 时修改变量。

volatile bool keepLoopGoing = true;
//loop
for (int i=0; keepLoopGoing ;i++)
    cout << i << endl;
//user input - separate thread
while ( keepLoopGoing )
{
   cin >> input;  // or getchar()
   if ( input == "s" )
      keepLoopGoing = false;
}

请注意,在按下任何内容之前,您很可能会溢出i