在Linux上使用kbhit()和getch() [英] Using kbhit() and getch() on Linux

查看:1320
本文介绍了在Linux上使用kbhit()和getch()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上,我有以下代码来查找输入,而不中断循环:

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;
    }
}

但是,看到没有 conio.h ,在Linux上实现这个最简单的方法是什么?

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

推荐答案

上面引用的ncurses如何帮助。下面是一个例子,说明如何使用ncurses如conio示例:

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");
    }
}

注意,对于ncurses, iostream 头不使用。这是因为混合stdio和ncurses可能有意想不到的结果。

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

ncurses,顺便说一句,定义 TRUE code> FALSE 。正确配置的ncurses将使用与ncurses bool 相同的数据类型作为用于配置ncurses的C ++编译器。

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.

这篇关于在Linux上使用kbhit()和getch()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆