Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 657
Boxiom Avatar asked Mar 29 '15 22:03

Boxiom


People also ask

What can I use instead of Kbhit?

The closest you can come is some sort of third party library that handles the portability issues for you. Curses probably comes the closest to doing that. Otherwise you have to write your own clear(), kbhit(), and getch() functions, with separate versions of each for each operating system.

How do you use Kbhit?

kbhit function is used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file “conio. h”. If a key has been pressed then it returns a non zero value otherwise returns zero.

What is Kbhit ()?

The kbhit is basically the Keyboard Hit. This function is present at conio. h header file. So for using this, we have to include this header file into our code. The functionality of kbhit() is that, when a key is pressed it returns nonzero value, otherwise returns zero.


2 Answers

If your linux has no conio.h that supports kbhit() you can look here for Morgan Mattews's code to provide kbhit() functionality in a way compatible with any POSIX compliant system.

As the trick desactivate buffering at termios level, it should also solve the getchar() issue as demonstrated here.

like image 120
Christophe Avatar answered Oct 14 '22 23:10

Christophe


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.

like image 40
Thomas Dickey Avatar answered Oct 15 '22 00:10

Thomas Dickey