如何用回车(回车)终止无限循环
How terminate infinite loop with enter(carriage return)
如何在按下Enter(回车)后立即终止此循环?我试过get ()!='r'(作为循环条件),但它需要按下键开始另一次迭代,并达到秒表的目的。
//To Create a stopwatch
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
int main ()
{
int milisecond=0;
int second=0;
int minutes=0;
int hour=0;
cout<<"Press any key to start Timer...."<<endl;
char start=_getch();
for(;;) //This loop needed to terminate as soon as enter is pressed
{
cout<<hour<<":"<<minutes<<":"<<second<<":"<<milisecond<<"r";
milisecond++;
Sleep(100);
if(milisecond==10)
{
second++;
milisecond=0;
}
if(second==60)
{
minutes++;
second=0;
}
if(minutes==60)
{
hour++;
minutes=0;
}
}
return(0);
}
为循环提供终止条件?
@BnBDim说kbhit()
将工作。如果您正在使用linux您可以从http://linux-sxs.org/programming/kbhit.html复制粘贴kbit .h/kbit .cpp并将其添加到您的项目中。
调用getch
会阻塞您的程序等待输入,相反,您可以使用kbhit()
检查是否按下了按钮,然后调用getch()
。
while(true)
{
if(kbhit())
{
char c = getch();
}
}
为了使用这两个函数,你必须包含<conio.h>
,它不是c++标准的一部分。
简单的跨平台版本:
#include <iostream>
#include <future>
#include <atomic>
#include <thread>
int main()
{
// a thread safe boolean flag
std::atomic<bool> flag(true);
// immediately run asynchronous function
// Uses a lambda expression to provide a function-in-a-function
// lambda captures reference to flag so we know everyone is using the same flag
auto test = std::async(std::launch::async,
[&flag]()
{
// calls to cin for data won't return until enter is pressed
std::cin.peek(); // peek leaves data in the stream if you want it.
flag = false; // stop running loop
});
// here be the main loop
while (flag)
{
// sleep this thread for 100 ms
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// do your thing here
}
}
文档:
-
std::atomic
-
std::async
- Lambda表达式
-
std::this_thread::sleep_for
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 当我在其中一个线程执行中(在activemq-cpp中)捕获到特定值时,我如何终止/停止所有其他线程
- llvm构建器向基本块添加终止符
- 如何使用隔离>终止执行来停止所有线程
- 用于将C++代码转换为 Web 程序集的脚本未终止
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- 终止 QProcess 不会终止子进程
- 运行代码时,c++ 会终止进程
- 检测到堆栈粉碎:已终止 中止(核心已转储)
- 在输入句子时终止 std::out_of_range
- 二进制搜索的终止点
- MPI:检查是否有任何进程已终止
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- while 循环不以哨兵值终止
- C++ 程序不会因为内存而终止
- 如何用回车(回车)终止无限循环