Is there a way to detect if a key has been pressed?

前端 未结 2 531
别跟我提以往
别跟我提以往 2021-01-27 02:51

I am compiling and executing my programs in cygwin on a windows computer. I am quite inexperienced in C but I would like a way to detect if a key has been pressed without prompt

2条回答
  •  长发绾君心
    2021-01-27 03:30

    I use the following function for kbhit(). It works fine on g++ compiler in Ubuntu.

    #include 
    #include 
    #include 
    int kbhit(void)
    {
      struct termios oldt, newt;
      int ch;
      int oldf;
    
      tcgetattr(STDIN_FILENO, &oldt);
      newt = oldt;
      newt.c_lflag &= ~(ICANON | ECHO);
      tcsetattr(STDIN_FILENO, TCSANOW, &newt);
      oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
      fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
    
      ch = getchar();
    
      tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
      fcntl(STDIN_FILENO, F_SETFL, oldf);
    
      if(ch != EOF)
      {
        ungetc(ch, stdin);
        return 1;
      }
    
      return 0;
    }
    

提交回复
热议问题