gpt4 book ai didi

控制 scanf() 接受任何输入的持续时间

转载 作者:行者123 更新时间:2023-11-30 15:24:59 29 4
gpt4 key购买 nike

我考虑过控制scanf来接受c中的任何输入。我的概念是等待10秒(或任何其他时间)来接受任何输入。10秒后它将退出并且不再接收任何输入。

 int main(){
int a,b,c,d;
scanf("%d",&a);
printf("10 seconds are over no more input");
}

这里我想控制输入的时间。10秒后,输入面板将不再保留,并且将打印文本“10秒结束,不再输入”。

最佳答案

#include <windows.h>
#include <stdio.h>

int main(void){
int num = 0;
DWORD waitCode;
printf("input number : ");
//wait console input 10,000 Millisecond
waitCode = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE) , 10*1000);
switch(waitCode){
case WAIT_TIMEOUT:
fprintf(stderr, "\n10 seconds are over no more input\n");
return -1;
case WAIT_OBJECT_0://normal status
scanf("%d", &num);//input from stdin buffer
if(num)//not zero
printf("input number is %d\n", num);
}
return 0;
}
<小时/>

添加
线程版本

#include <windows.h>
#include <stdio.h>

void ThreadProc(void *);

int main(void){
int num = 0;
DWORD waitCode;
DWORD ThreadID = 0;
HANDLE hThread = CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)ThreadProc,
(LPVOID)&num, 0, &ThreadID);
if(!hThread){
fprintf(stderr, "Failed to create a thread\n");
return -1;
}

waitCode = WaitForSingleObject(hThread, 10*1000);
switch(waitCode){
case WAIT_TIMEOUT:
fprintf(stderr, "\n10 seconds are over no more input\n");
break;
case WAIT_OBJECT_0://normal status
if(num)//not zero
printf("input number is %d\n", num);
}
CloseHandle(hThread);

return 0;
}

void ThreadProc(void *n){
int *num = n;
printf("input number : ");
scanf("%d", num);
ExitThread(0);
}

关于控制 scanf() 接受任何输入的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28130703/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com