Search code examples
c++loopsgetchar

How can I break a loop when a specific character has been hit?


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.


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
      }
    }