如何用回车(回车)终止无限循环

How terminate infinite loop with enter(carriage return)

本文关键字:回车 终止 无限循环 何用      更新时间:2023-10-16

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

文档:

  1. std::atomic
  2. std::async
  3. Lambda表达式
  4. std::this_thread::sleep_for