Search code examples
cwindowsvisual-c++getch

How to use kbhit and getch (C programming)


I'm trying to create a function that will printf a certain string if the user presses any button on the keyboard EXCEPT for capital P, if the user presses P then it will break the loop.

However I don't think I'm using _kbhit and _getch properly. I use the number 80 because that is the ASCII symbol for 80....sorry for any confusion

void activateAlarm(int channelID) {

    int key = 0;

    while(temperatureChannel[channelID].currentTemperature > temperatureChannel[channelID].highLimit
        ||temperatureChannel[channelID].currentTemperature < temperatureChannel[channelID].lowLimit) {

        beep(350,100);

        if (_kbhit()) {
            key = _getch();
            if(key == 'P');
                break;
        }    
    }
}

Solution

  • No need to explain, the code talks better :

    #include <conio.h>
    
    // ...
    
    printf("please press P key to pause \n ");
    
    int key = 0;
    
    while(1)
    {
        if (_kbhit())
        {
          key =_getch();
    
          if (key == 'P')
            break;
        }    
    }