2016-11-17 17 views
0

押されてEnter(キャリッジリターン)が発生するとすぐにこのループを終了させるにはどうすればよいですか? 私はgetch()!= '\ r'(ループ条件として)を試みましたが、別の反復を開始し、ストップウォッチの目的を打ち負かすにはkeyを押す必要があります。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

プラットフォーム固有の呼び出しなしでは実行できません。 More here:[入力が押されるのを待たずに標準入力から文字をキャプチャする](http://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to- ) – user4581301

答えて

0

getchを呼び出すと、プログラムが入力を待つのをブロックする代わりに、kbhit()を使用してボタンが押されたかどうかを確認し、getch()を呼び出すことができます。あなたがC++標準の一部ではない<conio.h>を含める必要があります両方の機能を使用するためには

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

1

As @BnBDimは、kbhit()がそのために働くでしょう。あなたがLinuxで作業している場合には kbhit.h y kbhit.cppをhttp://linux-sxs.org/programming/kbhit.htmlからコピーしてプロジェクトに追加することができます。

0

A単純なクロスプラットフォームのバージョン:

#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
関連する問題