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

时间:2015-03-29 18:07:55

标签: c windows console-application getchar

我基本上是一名初学C ++程序员......而且这是我第一次尝试用C语言编写代码。

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

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

请提出解决此问题的建议。

  

编辑:感谢您的建议,但是   我提出这个问题的主要动机是找到一个方法来中止getchar命令,即使用户没有输入任何东西......有什么建议吗?顺便说一句,我的平台是Windows

4 个答案:

答案 0 :(得分:3)

在我看来,最好的方法是使用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

选项。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:-1)

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