我正在做一个计数器,显示用户必须进行输入的秒数。问题是当我使用 scanf() 时,程序将停止并等待答案,但我不希望这样。即使用户没有输入任何内容,我也想继续运行计数器。
例子:
for(int i=10;i>=0;i--){
i==0? printf("time over\n"):printf("%d seconds left\n",i);
scanf("%s", decision);
sleep(1);
}
我该怎么做才能解决这个问题?
最佳答案
如评论中所述,一种可能性是使用轮询。
man poll
说:
poll() examines a set of file descriptors to see if some of them are ready for I/O or if certain events have occurred on them.
在代码中它可能是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/poll.h>
#include <stdbool.h>
int main() {
struct pollfd fds[1];
fds[0].fd = STDIN_FILENO;
fds[0].events = POLLIN;
bool dataAvailable = false;
for (int i = 10; i >= 0 && !dataAvailable; i--) {
switch (poll(fds, 1, 1000)) {
case -1:
perror("poll failed");
exit(1);
case 0:
printf("%d seconds left\n", i);
break;
default:
dataAvailable = true;
}
}
if (dataAvailable) {
//read from stdin
} else {
fprintf(stderr, "no input\n");
exit(1);
}
return 0;
}
关于c - C语言如何在不停止程序的情况下使用scanf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142912/