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

标签 c++ loops carriage-return

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

相关文章:

excel - 计算筛选工作表中的可见行数

matlab - matlab 中带有 nan 值的 z 分数(矢量化)

JavaScript Regexp - 允许回车可以让其他不需要的字符验证

c++ - unsigned int 和 unsigned long 都是 32 位的,但我不能在不强制转换的情况下混合使用它们……为什么?

c++ - 翻转从 Kinect 收到的深度帧

php使用循环重新启动脚本执行的时间限制

C++ 标记化字符串不可取消引用

c++ - 将char数组传递给函数C++

bash - shell中实时去除回车