c++linuxgetchconiokbhit

Using kbhit() and getch() on Linux


On Windows, I have the following code to look for input without interrupting the loop:

#include <conio.h>
#include <Windows.h>
#include <iostream>

int main()
{
    while (true)
    {
        if (_kbhit())
        {
            if (_getch() == 'g')
            {
                std::cout << "You pressed G" << std::endl;
            }
        }
        Sleep(500);
        std::cout << "Running" << std::endl;
    }
}

However, seeing that there is no conio.h, whats the simplest way of achieving this very same thing on Linux?


Solution

  • The ncurses howto cited above can be helpful. Here is an example illustrating how ncurses could be used like the conio example:

    #include <ncurses.h>
    
    int
    main()
    {
        initscr();
        cbreak();
        noecho();
        scrollok(stdscr, TRUE);
        nodelay(stdscr, TRUE);
        while (true) {
            if (getch() == 'g') {
                printw("You pressed G\n");
            }
            napms(500);
            printw("Running\n");
        }
    }
    

    Note that with ncurses, the iostream header is not used. That is because mixing stdio with ncurses can have unexpected results.

    ncurses, by the way, defines TRUE and FALSE. A correctly configured ncurses will use the same data-type for ncurses' bool as the C++ compiler used for configuring ncurses.