gpt4 book ai didi

c++ - 如何使用 enter(回车)终止无限循环

转载 作者:行者123 更新时间:2023-11-28 05:25:22 25 4
gpt4 key购买 nike

如何在按下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com