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

How to abort getchar() command in C?

我基本上是一个初学者 C++ 程序员...这是我第一次尝试用 C 编写代码。

我正在尝试编写贪吃蛇游戏(使用 system ("cls"))。

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

请给出解决这个问题的建议。

EDIT: Thanks for the suggestions, but My main motive of asking this question was to find a method to abort the getchar command even if the user has not entered anything....Any suggestions on this? And by the way my platform is windows

在类 UNIX 平台(例如 Linux)上执行此操作的方法是使用 select 函数。您可以找到它的文档 online。我不确定 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

选项。

您可以生成一个新线程,该线程可以在 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() 之前终止线程。

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

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