Question

Assume I have a loop like

for(int i = 0; i < 100000; i++)
{
    crunch_data(i);

    if(i_has_been_hit())
        break;
}

and I would like to exit the loop whenever I hit i on the keyboard. Now the following approach won't work, since std::cin blocks:

bool i_has_been_hit(){
    char a;
    std::cin >> a;
    return a == 'i';
}

Is there a function which enables me to check whether the keyboard has been hit without blocking? If it makes any difference, I'm using g++ on Win32 with CodeBlocks.

Était-ce utile?

La solution

If you are using Win32 with conio.h available, you can use the usual kbhit() and getch() combination:

#include <conio.h>
#include <iostream>

int main(){
  for(int i=0;i<100000;i++)
  {
      std::cout<<"Hi";
      if(kbhit() && getch() == 'i'){
          break;
      }
      // other code
  }
}

Autres conseils

Did you mean a perfect non-blocking I/O model ?? If so its hard to achive and i dont know any existing ways to do it, But u can do something like this

use _kbhit()

for(int i=0;i<100000;i++)
{
    cout<<"Hi";
    while (true) {
          if (_kbhit()) {
        char a = _getch();
        // act on character a in whatever way you want
    }

    Sleep(100);
    if(a=='i')
       break;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top