要让'scanf'不阻塞,可以使用以下方法:

  1. 使用'fgets'替代'scanf'函数。'fgets'函数可以读取一行输入,并将其存储在指定的缓冲区中。这样,即使没有输入,程序也不会被阻塞。
char buffer[100];
fgets(buffer, sizeof(buffer), stdin);
  1. 使用非阻塞(non-blocking)的输入函数。在某些操作系统中,可以使用特定的函数将标准输入设置为非阻塞模式。例如,在Linux上,可以使用'fcntl'函数来设置文件描述符为非阻塞模式。
#include <fcntl.h>

int main() {
    int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
    fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
    
    // 此后的scanf函数将不会阻塞
    char buffer[100];
    scanf("%s", buffer);
    
    return 0;
}
  1. 使用多线程。在单独的线程中运行'scanf'函数,这样主线程可以继续执行其他任务而不被阻塞。可以使用线程库(如pthread库)来创建线程。
#include <pthread.h>

void* scan_input(void* arg) {
    char buffer[100];
    scanf("%s", buffer);
    return NULL;
}

int main() {
    pthread_t thread_id;
    pthread_create(&thread_id, NULL, scan_input, NULL);
    
    // 主线程可以继续执行其他任务
    
    pthread_join(thread_id, NULL);
    
    return 0;
}

请注意,以上方法中的第2和第3种方法需要在特定的操作系统上使用,并且可能不是跨平台的。因此,最好使用第1种方法,使用'fgets'替代'scanf'来避免阻塞。

如何避免 scanf 阻塞:使用 fgets 和 其他方法

原文地址: https://www.cveoy.top/t/topic/pPfI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录