【问题标题】:Continue code if user input isn't given C如果未给出用户输入,则继续代码 C
【发布时间】:2022-11-11 18:12:29
【问题描述】:

我的问题如下:

如果过了一定时间,有没有办法继续我的代码并跳过输入

例如 :

printf("How old are you");

int age;
scanf("%d",&age);
// I don't know how to check if the time has been exeeded
sleep(5)

if("Time exeeded"){
 printf("It's seems like the user is not there\n\n Goodbye");
 return 1;

}
else {
 printf("You are %d",age);
 return 0;
}

谢谢您的回答

【问题讨论】:

  • 您需要在这里运行两个不同的线程(这是使用semaphores 的上下文)。
  • 我必须把研究重点放在 sem_wait 和 sem_post 上吗?
  • 你不能用标准 C 来解决这个问题。你需要一个不阻塞的输入函数。这将是特定于操作系统的。

标签: c input semaphore sleep


【解决方案1】:

典型的解决方案是在select 上使用超时:

/* Set a 10 second timer on a scanf */

#include <unistd.h>
#include <stdio.h>
int
main(void)
{
    struct timeval tp = { .tv_sec = 10, .tv_usec = 0 };
    char b[32];
    fd_set fds;

    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    switch( select(STDIN_FILENO + 1, &fds, NULL, NULL, &tp) ){
    case 1:
        if( FD_ISSET(STDIN_FILENO, &fds) ){
            if( scanf("%31s", b) == 1 ){
                printf("Read: %s
", b);
            }
        }
        break;
    case 0:
        puts("Timeout");
        break;
    default:
        fputs("Error
", stderr);
    }
}

【讨论】:

  • 注意:如果用户弄乱了他们的终端设置,他们可能能够发送一些字符,但不能发送整个字符串。所以 scanf 可能仍会等待字符串的其余部分,而不会超时。
猜你喜欢
  • 2016-11-03
  • 2013-04-06
  • 2022-01-08
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 2023-02-23
  • 1970-01-01
相关资源
最近更新 更多