Check keypress in C++ on Linux

后端 未结 2 422
春和景丽
春和景丽 2020-12-19 07:37

Is there an easy way to check if a key is being pressed so I can loop through that in a thread? Preferred not to use a library and definitely not ncurses. There isn\'t a sin

2条回答
  •  执笔经年
    2020-12-19 08:11

    Try this:-

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        struct termios oldSettings, newSettings;
    
        tcgetattr( fileno( stdin ), &oldSettings );
        newSettings = oldSettings;
        newSettings.c_lflag &= (~ICANON & ~ECHO);
        tcsetattr( fileno( stdin ), TCSANOW, &newSettings );    
    
        while ( 1 )
        {
            fd_set set;
            struct timeval tv;
    
            tv.tv_sec = 10;
            tv.tv_usec = 0;
    
            FD_ZERO( &set );
            FD_SET( fileno( stdin ), &set );
    
            int res = select( fileno( stdin )+1, &set, NULL, NULL, &tv );
    
            if( res > 0 )
            {
                char c;
                printf( "Input available\n" );
                read( fileno( stdin ), &c, 1 );
            }
            else if( res < 0 )
            {
                perror( "select error" );
                break;
            }
            else
            {
                printf( "Select timeout\n" );
            }
        }
    
        tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
        return 0;
    }
    

    From here

提交回复
热议问题