【发布时间】:2018-08-21 22:03:39
【问题描述】:
我已经为此烦恼了好几个小时了。基本上,我有一个程序要求用户输入他的密码 (123),如果用户在 5 秒 内没有输入任何内容,那么程序将退出(游戏结束)。我一直在尝试使用 time(NULL) 和 clock() 但仍然没有运气。谁能指出我正确的方向,好吗?提前非常感谢!
这是我的代码:
#include <stdio.h>
#include <time.h>
int main(){
int password = 0;
int num = 0;
printf("%s\n", "Please enter your password");
scanf("%d", &password);
// Here I need to check if user didnt enter anything for 5 seconds,
// and if he didnt enter anything then exit out of the program
// I tried using time
// time_t start = time(NULL);
// time_t stop = time(NULL);
// if(((stop - start) * 1000) > 5000){
// printf("%s\n", "Game Over");
// break;
// }
printf("%s\n", "Thank you for entering your password, now enter any number");
scanf("%d", &num);
return 0;
}
【问题讨论】:
-
我的 2 美分是这个任务需要进程或线程
-
不要使用
break作为初学者使用return 0,scanf也是一个阻塞调用,你需要使用fork或类似的东西来完成你想要的 -
@snr线程如何实现?
-
@Mitchel0022 在使用 return 0 后如何让它工作并在 5 秒后退出程序,如果用户没有输入任何内容?
-
启动一个休眠 5 秒的 pthread 然后检查原子的“用户输入的内容”标志并在未设置时终止进程是相当简单的。这样做比使用 select() 更容易。
标签: c