我想制作一个代码,要求输入用户名,但时间限制为 15 秒。如果用户超过限制并且未能输入名称(或任何字符串),则代码将终止并显示“超时”消息,否则应保存名称并显示“谢谢”消息。我曾这样尝试过,但它是错误的并且不起作用。请给我一个解决方案..谢谢。
#include <stdio.h>
#include <time.h>
int timeout ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
return 1;
}
int main ()
{
char name[20];
printf("Enter Username: (in 15 seconds)\n");
printf("Time start now!!!\n");
scanf("%s",name);
if( timeout(5) == 1 ){
printf("Time Out\n");
return 0;
}
printf("Thnaks\n");
return 0;
}
最佳答案
也许这个虚拟程序可以帮助您:
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#define WAIT 3
int main ()
{
char name[20] = {0}; // in case of single character input
fd_set input_set;
struct timeval timeout;
int ready_for_reading = 0;
int read_bytes = 0;
/* Empty the FD Set */
FD_ZERO(&input_set );
/* Listen to the input descriptor */
FD_SET(STDIN_FILENO, &input_set);
/* Waiting for some seconds */
timeout.tv_sec = WAIT; // WAIT seconds
timeout.tv_usec = 0; // 0 milliseconds
/* Invitation for the user to write something */
printf("Enter Username: (in %d seconds)\n", WAIT);
printf("Time start now!!!\n");
/* Listening for input stream for any activity */
ready_for_reading = select(1, &input_set, NULL, NULL, &timeout);
/* Here, first parameter is number of FDs in the set,
* second is our FD set for reading,
* third is the FD set in which any write activity needs to updated,
* which is not required in this case.
* Fourth is timeout
*/
if (ready_for_reading == -1) {
/* Some error has occured in input */
printf("Unable to read your input\n");
return -1;
}
if (ready_for_reading) {
read_bytes = read(0, name, 19);
if(name[read_bytes-1]=='\n'){
--read_bytes;
name[read_bytes]='\0';
}
if(read_bytes==0){
printf("You just hit enter\n");
} else {
printf("Read, %d bytes from input : %s \n", read_bytes, name);
}
} else {
printf(" %d Seconds are over - no data input \n", WAIT);
}
return 0;
}
更新:
这是经过测试的代码。
此外,我还从 man 那里获得了有关 select
的提示。本手册已经包含一个代码片段,用于在没有事件的情况下从终端读取并在 5 秒内超时。
只是一个简短的解释,以防代码写得不够好:
- 我们将输入流 (
fd = 1
) 添加到 FD 集中。 - 我们启动
select
调用来收听为创建的这个 FD 集 任何事件。 - 如果在
timeout
时间内发生任何事件,即 通读read
调用。 - 如果没有事件,则会发生超时。
希望这对您有所帮助。
关于c - 超时功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226603/