Exits the loop after a certain amount of time if there's no input

后端 未结 3 1397
南方客
南方客 2021-01-19 03:22

I\'m just wondering whether is it possible and how do I implement this feature, where we exit from the loop if there\'s no input from the user. For example, I want to exit t

3条回答
  •  Happy的楠姐
    2021-01-19 03:42

    Use select() function to set a timeout for your scanf

    The following code is an example of how use it.

    #include 
    #include 
    #include 
    
    int main(void)
    {
        int x;
        fd_set          set;
        struct          timeval timeout = {0};
    
        FD_ZERO(&set);
    
    
       while(1)
       {
            timeout.tv_sec = 30;
            FD_SET(fileno( stdin ), &set);
            printf ("enter a number:");
            fflush (stdout);
            if (select(FD_SETSIZE, &set, NULL, NULL, &timeout))
            {
    
               scanf("%d", &x);
               printf("The number you put is %d\r\n",x);
    
            }
            else
            {
                    printf("\r\nTimeout: Stop reading\r\n");
                    break;
            }
        }
    }
    

提交回复
热议问题