Is there a way to get user input without pressing the enter key?

前端 未结 2 1965
栀梦
栀梦 2021-01-02 01:56

I\'m programming a console game, (pac-man), and I was wondering how I would get user input without them pressing the enter key. I looked around the internet a little and I f

2条回答
  •  感动是毒
    2021-01-02 02:26

    This works for me (I am on linux):

    #include 
    #include 
    #include 
    
    int main()
    {
        struct termios old_tio, new_tio;
        unsigned char c;
    
        /* get the terminal settings for stdin */
        tcgetattr(STDIN_FILENO,&old_tio);
    
        /* we want to keep the old setting to restore them a the end */
        new_tio=old_tio;
    
        /* disable canonical mode (buffered i/o) and local echo */
        new_tio.c_lflag &=(~ICANON & ~ECHO);
    
        /* set the new settings immediately */
        tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);
    
        do {
             c=getchar();
             printf("%d ",c);
        } while(c!='q');
    
        /* restore the former settings */
        tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);
    
        return 0;
    }
    

    It makes the console unbuffered.

    reference: http://shtrom.ssji.net/skb/getc.html

提交回复
热议问题