通过实时按键停止循环
Stop a loop by pressing a key in real-time
我写了一个简单的计时器。通过按"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
。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 通过实时按键停止循环
- 我将如何在 c++ 中创建一个实时更新覆盖上一个条目的循环
- SFML 2实时文本输入?(无事件循环)
- 实时音频,快速循环中的临时缓冲区,不同的方法
- 设置C++代码中while循环的执行速率以进行实时同步