How to capture keyboard action without pausing the C ++ program?

4

How do I capture a keyboard action without pausing the program? For example:

char tecla;
do{
    scanf("%c", &tecla);
    printf("%c",tecla); 
}while(tecla != '0');

I wanted it to loop, but when typing something on the keyboard I was able to capture and execute a certain action within the program. The program will run in the terminal, with each loop and I will clean the screen and print other things again.

    
asked by anonymous 07.11.2014 / 17:08

2 answers

4

This can not be done with pure C ++ since it depends on the operating system and console used. ( Font )

An alternative is to use the kbhit() function available in the conio.h library. It checks if any keys have been pressed, so just call the function before scanf . However, we need to look at why there are distinct implementations for Windows and Linux . ( Font )

In Windows, you can also use the ReadConsoleInput to read and empty the console input buffer. Note that this function also captures mouse events, so you need to check the event type received .

One consideration for all this is that, depending on what you want, it is not good to do checks in a loop. That wastes CPU. One approach to solving this is to create new threads to make the processing "heavy" and leave the main thread responsible for reading and writing on the console.

    
07.11.2014 / 20:29
3

I found this link to my answer

kbhit

char tecla;
do{
if(kbhit()){
    tecla = getch();

    switch(tecla){
        case 'W': //cima
            break;
        case 'S': //baixo
            break;
    }
}
//executo meu programa bazeado na tecla
}while(tecla != '0');

The kbhit() function identifies when an action occurs on the keyboard, but it is only present in the <conio.h> header that was made exclusively for MS / DOS. So it will not work if you're using a MacOSX.

    
07.11.2014 / 20:30