c++ breaking out of loop by key press at any time -


what have here loop supposed read output on piece of equipment every 500 milliseconds. part works fine. however, when try introduce cin.get pick key "n" being pressed stop loop, many outputs number of key presses point. if press keys (apart 'n') several times followed enter, few more outputs. need loop keep looping without interaction until want stop.

here's code:

for(;;) {     count1++;     sleep(500);     analoginput = readanalogchannel(1) / 51.0;     cout << count1*0.5 << "     " << analoginput << endl;     outputfile << count1*0.5 << ", " << analoginput << endl;     if (cin.get() == 'n') //problem starts introduced         break; }; 

my output follows (there 2 key presses stage in program) unless press few more keys followed enter:

0.5    0 // expected 1      2 // expected should more values until stopped 

i have no particular preference in type of loop use, long works.

thanks!

cin.get() synchronous call, suspends current thread of execution until gets input character (you press key).

you need run loop in separate thread , poll atomic boolean, change in main thread after cin.get() returns.

it this:

std::atomic_boolean stop = false;  void loop() {     while(!stop)     {         // loop body here     } }  // ...  int main() {     // ...     boost::thread t(loop); // separate thread loop.     t.start(); // starts thread.      // wait input character (this suspend main thread, loop     // thread keep running).     cin.get();      // set atomic boolean true. loop thread exit      // loop , terminate.     stop = true;      // ... other actions ...      return exit_success;  } 

note: above code give idea, uses boost library , latest version of standard c++ library. may not available you. if so, use alternatives environment.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -