gpt4 book ai didi

c++ - kbhit() 在 MacOS 上检测按键

转载 作者:行者123 更新时间:2023-11-30 03:12:48 28 4
gpt4 key购买 nike

我是 MacOS 上的 C++ 新手。我在使用 kbhit() 时出错在我的程序中。

我用了#include<conio.h>但也有错误,所以我搜索并测试了 #include<curses.h>但错误仍然存​​在。

最佳答案

不知道这是否适用于 Mac,但这是我用来在 Linux 上获得单个按键的一些代码。

int mygetch() {
char ch;
int error;
static struct termios Otty, Ntty;

fflush(stdout);
tcgetattr(0, &Otty);
Ntty = Otty;

Ntty.c_iflag = 0; /* input mode */
Ntty.c_oflag = 0; /* output mode */
Ntty.c_lflag &= ~ICANON; /* line settings */

#if 1
/* disable echoing the char as it is typed */
Ntty.c_lflag &= ~ECHO; /* disable echo */
#else
/* enable echoing the char as it is typed */
Ntty.c_lflag |= ECHO; /* enable echo */
#endif

Ntty.c_cc[VMIN] = CMIN; /* minimum chars to wait for */
Ntty.c_cc[VTIME] = CTIME; /* minimum wait time */

#if 1
/*
* use this to flush the input buffer before blocking for new input
*/
#define FLAG TCSAFLUSH
#else
/*
* use this to return a char from the current input buffer, or block if
* no input is waiting.
*/
#define FLAG TCSANOW

#endif

if ((error = tcsetattr(0, FLAG, &Ntty)) == 0) {
error = read(0, &ch, 1 ); /* get char from stdin */
error += tcsetattr(0, FLAG, &Otty); /* restore old settings */
}

return (error == 1 ? (int) ch : -1 );
}

关于c++ - kbhit() 在 MacOS 上检测按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/312185/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com