在 Linux 上使用 kbhit() 和 getch() [英] Using kbhit() and getch() on Linux
问题描述
在 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 howto 可能会有所帮助.这是一个示例,说明如何像 conio 示例一样使用 ncurses:
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
");
}
napms(500);
printw("Running
");
}
}
请注意,对于 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
和 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屋!