Home > Backend Development > C++ > body text

How to Emulate `kbhit()` and `getch()` Functionality on Linux?

Susan Sarandon
Release: 2024-10-31 03:45:01
Original
276 people have browsed it

How to Emulate `kbhit()` and `getch()` Functionality on Linux?

Emulating kbhit() and getch() Functionality on Linux

The kbhit() and getch() functions are commonly used in Windows to check for input without interrupting the execution of a loop. However, these functions are not natively supported on Linux operating systems.

The kbhit() Equivalent

To achieve similar functionality on Linux, you can utilize Morgan Mattews's implementation of the kbhit() function. This implementation is compatible with POSIX-compliant systems and can be found here.

The getch() Equivalent

Since kbhit() deactivates buffering at the termios level, it also addresses the getchar() issue. You can use getchar() as-is without disabling buffering as in the provided Windows example.

Combining Both Functions

Once you have implemented the kbhit() functionality, you can adapt the Windows example to Linux as follows:

<code class="C++">#include <unistd.h>
#include <iostream>

int main()
{
    while (true)
    {
        if (kbhit())
        {
            int key = getch();
            if (key == 'g')
            {
                std::cout << "You pressed G" << std::endl;
            }
        }
        usleep(500000);
        std::cout << "Running" << std::endl;
    }
}</code>
Copy after login

The above is the detailed content of How to Emulate `kbhit()` and `getch()` Functionality on Linux?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!