如何在C中监听用户输入时运行程序?

我正在尝试制作一个继续运行的游戏,直到按下一个键,然后它应该接受该键并对其执行某些操作然后按照正常情况继续运行。 我该怎么做呢?

我在MAC上,所以尽管我遇到了一个名为conio.h的windows库,它可以使用kbhit()和getch()来处理这个问题,我无法让它为我工作……

// // main.c // conioTesting // // #include  #include "myconio_mac.h" int main(int argc, const char * argv[]) { int counter = 0; while (counter < 2) { if (kbhit()) { char key = getch(); printf("\n Key is %c \n", key); printf("Keyboard hit detected \n"); } else { printf("Nothing. \n"); } } printf("Passed!!!!!!!!!! \n"); } 

在MAC上,您需要调整终端设置以关闭线路缓冲。 (您也可以关闭回声。)正确设置终端后,您可以使用read从键盘获取单个字符。

在下面的示例代码中, kbsetup函数负责终端设置。 getkeyfunction检查按键,如果有,则返回键,如果没有键,则返回'\0'main函数有一个循环,每秒打印一次,并打印用户按下的任何键。 按'q'退出程序。

 #include  #include  #include  #include  #include  #include  static struct termios oldSettings; void kbcleanup( void ) { tcsetattr( 0, TCSAFLUSH, &oldSettings ); /* restore old settings */ } void kbsetup( void ) { tcgetattr( 0, &oldSettings ); struct termios newSettings = oldSettings; newSettings.c_lflag &= ~ICANON; /* disable line-at-a-time input */ newSettings.c_lflag &= ~ECHO; /* disable echo */ newSettings.c_cc[VMIN] = 0; /* don't wait for characters */ newSettings.c_cc[VTIME] = 0; /* no minimum wait time */ if ( tcsetattr( 0, TCSAFLUSH, &newSettings ) == 0 ){ atexit( kbcleanup ); /* restore the terminal settings when the program exits */ } else { fprintf( stderr, "Unable to set terminal mode\n" ); exit( 1 ); } } int getkey( void ) { char c; if ( read( STDIN_FILENO, &c, 1 ) == 0 ) return '\0'; else return c; } int main( void ) { int c; kbsetup(); time_t start = time( NULL ); time_t previous = start; for (;;) { usleep( 1000 ); time_t current = time( NULL ); if ( current != previous ) { fprintf( stderr, "tick %3ld\r", current - start ); previous = current; } else if ( (c = getkey()) != '\0' ) { if ( c == 'q' || c == 'Q' ) break; printf( "\ngot char: 0x%02x", c ); if ( isprint( c ) ) printf( " '%c'", c ); printf( "\n" ); } } } 

听起来你想要等待按键然后继续执行:

 //test.c #include  #include  void *input_listener(void *threadarg) { getchar(); printf("A key was pressed.\n"); } int main() { printf("Start\n"); pthread_t thread; pthread_create(&thread, NULL, input_listener, NULL); pthread_join(thread, NULL); // Continue main } 

用pthreads应该很简单(需要编译: gcc test.c -lpthread )。

您可以查看另一个stackoverflowpost中提到的答案:

Linux的kbhit()[和getch()]问题