2

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.

Zeta
  • 103,620
  • 13
  • 194
  • 236
Vio
  • 43
  • 6

2 Answers2

0

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;
}
Amarnath R Shenoy
  • 5,121
  • 8
  • 24
  • 32
0

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
  }
}
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • @user3260217: You would have gotten answers sooner if your question's quality was higher. Please try to write the perfect question next time, see http://java.dzone.com/articles/how-write-perfect and https://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx for guidelines. – Zeta Mar 27 '14 at 13:01