如何中止在C中的getchar()命令?

我基本上是一个初学C ++程序员…这是我第一次尝试在C

我试图system ("cls")一个蛇游戏(使用system ("cls") )。

在这个程序中,我需要获得一个字符作为input(基本上是为了让用户改变蛇的运动方向)…如果在半秒内没有input任何字符,那么这个字符input命令需要被中止,我的剩余的代码应该被执行。

请提出build议来解决这个问题。

编辑:谢谢你的build议,但我问这个问题的主要动机是find一种方法来中止getchar命令,即使用户没有input任何东西….任何build议呢? 顺便说一下,我的平台是windows

在我看来,最好的方法是使用libncurses。

http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/

你有所有的工具来轻松地制作一条蛇。

如果你觉得这太容易了(这是一个相对较高水平的图书馆),看看termcaps图书馆。

编辑:所以,与termcaps非阻塞阅读是:

 #include <termios.h> #include <unistd.h> #include <term.h> uintmax_t getchar() { uintmax_t key = 0; read(0, &key, sizeof(key)); return key; } int main(int ac, char **av, char **env) { char *name_term; struct termios term; if ((name_term = getenv("TERM")) == NULL) // looking for name of term return (-1); if (tgetent(NULL, &name_term) == ERR) // get possibilities of term return (-1); term.c_lflag &= ~(ICANON | ECHO); term.c_cc[VMIN] = 0; term.c_cc[VTIME] = 0; // non-blocking read if (tcgetattr(0, term) == -1) // applying modifications. return (-1); /* Your code here with getchar() */ term.c_lflag &= (ICANON | ECHO); if (tcgetattr(0, term) == -1) // applying modifications. return (-1); return (0); } 

编辑2:你必须编译

-lncurses

选项。

在类UNIX平台(如Linux)上执行此操作的方法是使用select函数。 你可以在网上找到它的文档。 我不确定这个函数是否在Windows上可用; 你没有指定一个操作系统。

我在@eryksun发表的评论中得到了最适合我的问题的答案。

最好的方法是使用函数kbhit() (conio.h的一部分)。

您可以产生一个新的线程,可以模拟30秒后按Enter键。

 #include <windows.h> #include <stdio.h> #pragma comment(lib, "User32.lib") void ThreadProc() { // Sleep for 30 seconds Sleep(30*1000); // Press and release enter key keybd_event(VK_RETURN, 0x9C, 0, 0); keybd_event(VK_RETURN, 0x9C, KEYEVENTF_KEYUP, 0); } int main() { DWORD dwThreadId; HANDLE hThread = CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)ThreadProc, NULL, 0,&dwThreadId); char key = getchar(); // you are out of getchar now. You can check the 'key' for a value of '10' to see if the thread did it. // Kill thread before you do getchar again } 

小心这个技巧,特别是如果你在一个循环中做geatchar(),否则你可能会得到很多线程按ENTER键! 再次启动getchar()之前,一定要杀死线程。