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

标签 c++ macos

我是 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/

相关文章:

c++ - Netbeans 7.3 构建主机 c/cpp

c++函数返回 vector 中的最小正整数

java - 在 Java 中分析 native 方法 - 奇怪的结果

未加载 PHP 配置文件? (Mac OS X 优胜美地)

python - 如何使用 PyObjC 绑定(bind)和 NSMetadataQuery 编写与 mdfind 等效的 python 脚本?

c++ - 通过继承和交叉委托(delegate)实现代码重用

具有常量构造函数参数的 C++ 变量构造函数方法

c++ - 是否有一个自动源代码格式化程序可以很好地包装 C/C++ 行?

objective-c - 如何知道应用程序运行在哪个 Mac OS 上?

macos - 在 mac os x 中使用 qtcreator 和 gnu g++4.8