1

I am new to C++ on MacOS. I got an error when I used kbhit() in my program.

I used #include<conio.h> but got error too, so I searched and test with #include<curses.h> but error is still remained.

vvvvv
  • 25,404
  • 19
  • 49
  • 81

2 Answers2

2

No idea if this would work on Mac, but here's some code that I've used to get a single keypress on Linux.

int mygetch() {
    char ch;
    int error;
    static struct termios Otty, Ntty;

    fflush(stdout);
    tcgetattr(0, &Otty);
    Ntty = Otty;

    Ntty.c_iflag  =  0;     /* input mode       */
    Ntty.c_oflag  =  0;     /* output mode      */
    Ntty.c_lflag &= ~ICANON;    /* line settings    */

#if 1
    /* disable echoing the char as it is typed */
    Ntty.c_lflag &= ~ECHO;  /* disable echo     */
#else
    /* enable echoing the char as it is typed */
    Ntty.c_lflag |=  ECHO;  /* enable echo      */
#endif

    Ntty.c_cc[VMIN]  = CMIN;    /* minimum chars to wait for */
    Ntty.c_cc[VTIME] = CTIME;   /* minimum wait time    */

#if 1
    /*
    * use this to flush the input buffer before blocking for new input
    */
    #define FLAG TCSAFLUSH
#else
    /*
    * use this to return a char from the current input buffer, or block if
    * no input is waiting.
    */
    #define FLAG TCSANOW

#endif

    if ((error = tcsetattr(0, FLAG, &Ntty)) == 0) {
        error  = read(0, &ch, 1 );        /* get char from stdin */
        error += tcsetattr(0, FLAG, &Otty);   /* restore old settings */
    }

    return (error == 1 ? (int) ch : -1 );
}
Evan Teran
  • 87,561
  • 32
  • 179
  • 238
1

kbhit() is non-standard. In fact, I don't believe there is a standard function for detecting keyboard input. The best you can do is read a character from stdin using e.g. fgetc, and hope it's not redirected from somewhere else.

strager
  • 88,763
  • 26
  • 134
  • 176