我想控制scanf以获取c.my概念中的任何输入是关于等待10秒(或任何其他时间)接受任何输入。在10秒后它将退出并且将不再接收任何输入。
int main(){
int a,b,c,d;
scanf("%d",&a);
printf("10 seconds are over no more input");
}
这里我想控制输入的时间。在10秒之后输入面板将不再保留,并且将打印文本“10秒结束不再输入”。
答案 0 :(得分:1)
#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);
}