How to run program whilst listening for user input in C?

后端 未结 2 2027
庸人自扰
庸人自扰 2020-12-03 19:59

I\'m trying to make a game that continues running until a key is pressed and then it should take that key in and do something with it then continue running as per normal. Ho

2条回答
  •  生来不讨喜
    2020-12-03 20:45

    Sounds like you want to wait for a key to be pressed and then continue execution:

    //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
    }
    

    Should be very simple to do with pthreads (need to compile: gcc test.c -lpthread).

提交回复
热议问题