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

时间:2016-11-17 21:47:05

标签: 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);
}

提供循环的终止条件?

3 个答案:

答案 0 :(得分:1)

正如@BnBDim所说,kbhit()将为此工作。如果您正在使用Linux 你可以从http://linux-sxs.org/programming/kbhit.html复制粘贴kbhit.h和kbhit.cpp并将其添加到你的项目中。

答案 1 :(得分:0)

调用getch阻止您的程序等待输入,而您可以使用kbhit()检查按钮是否已被按下,然后拨打getch()

while(true)
{
    if(kbhit())
    {
        char c = getch();
    }
}

为了使用这两个函数,您必须包含<conio.h>,这不是C ++标准的一部分。

答案 2 :(得分:0)

一个简单的跨平台版本:

#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 Expressions
  4. std::this_thread::sleep_for