如何在按下 Enter(回车)后立即终止此循环? 我试过 getch()!='\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 复制粘贴 kbhit.h y kbhit.cpp并将其添加到您的项目中。
关于c++ - 如何使用 enter(回车)终止无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665633/