简体   繁体   English

Mac中的kbhit()

[英]kbhit() in mac

I am new to cpp in mac. 我是Mac中cpp的新手。 I got error when I used kbhit() in my program. 在程序中使用kbhit()时出现错误。 I used #include but got error too, so I searched and test with #include but error is still remained. 我使用了#include但也出现了错误,因此我使用#include进行了搜索和测试,但错误仍然存​​在。 so plz help me. 所以请帮助我。 thanks in advance. 提前致谢。

No idea if this would work on Mac, but here's some code that I've used to get a single keypress on Linux. 不知道这是否可以在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 );
}

kbhit() is non-standard. kbhit()是非标准的。 In fact, I don't believe there is a standard function for detecting keyboard input. 实际上,我认为没有用于检测键盘输入的标准功能。 The best you can do is read a character from stdin using eg fgetc, and hope it's not redirected from somewhere else. 最好的办法是使用fgetc等从stdin中读取一个字符,并希望它不会从其他位置重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM