2016-11-17 184 views
0

如何在按下Enter(回車)按鈕時立即終止此循環? 我曾嘗試getch()!='\ r'(作爲循環條件),但它需要按鍵來開始另一個迭代並擊敗秒錶的目的。如何用enter終止無限循環(回車)

//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); 
} 

提供循環的終止條件?

+1

使用ctrl-z或ctrl-c有問題嗎? – Adalcar

+0

ctrl-z只是終止了整個程序,但我需要在循環工作結束後繼續工作。存儲停止時間 –

+0

如果沒有平臺特定的調用,則無法完成。更多在這裏:[從標準輸入中捕獲字符而不等待輸入被按下](http://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-被按下?) – user4581301

回答

0

調用getch會阻止程序等待輸入,而您可以使用kbhit()來檢查按鈕是否已被按下,然後調用getch()

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

爲了使用這兩種功能必須包含<conio.h>其不是C++標準的一部分。

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