사용자가 질문을하고 몇 초 내에 질문에 답하는 프로그램을 만들려고합니다. 그렇지 않으면 프로그램이 입력을 중지합니다.논 블로킹 입력 C
내 문제는 내 프로그램이 입력을 차단하지 못하게하는 것입니다. 데이터를 입력 할 수 있지만 입력하지 않으면 타이머가 끊어져 계속 입력을 요청합니다.
Windows에서 실행 중이며 Code :: Blocks를 사용하는 것이 중요합니다. 누군가 내가 잘못하고있는 것을 나에게 설명 할 수 있다면 그것은 인정 될 것이다. 시간이 timeleft()
이 questions()
에 따라 시험 할 때, 글로벌 플래그를 설정하고, 설정 코드를 만드는 경우 한 뛰쳐
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <conio.h>
int key = 0;
int GradeTotal = 0;
//runs an empty loop every iteration F.E. for loop
void timer(int seconds)
{
clock_t wait = (clock() + (seconds * CLOCKS_PER_SEC));
while(clock() < wait){}
}
void timeleft()
{
int index;
for(index = 5; index >= 0; index--)
{
if(key != 0)
{
pthread_exit(timeleft);
}
timer(1);
if(index == 0)
{
printf("\n\nTime's up!");
}
}
}
void questions()
{
int key;
printf("what is 1 + 1?\nAnswer: ");
while(1)
{
if(_kbhit())
{
key = _getch();
printf("%c",key);
break;
}
}
if(key == 50)
{
GradeTotal += 1;
}
}
int main()
{
pthread_t thread1,thread2;
int index;
int seconds = 0;
pthread_create(&thread1, NULL, questions, NULL);
pthread_create(&thread2, NULL, timeleft, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("\n\nGrade: %d",GradeTotal);
return 0;
}
'while (clock()
Stargateur
질문 : https://stackoverflow.com/questions/28382962/wait-for-press-enter-in-c-inside-a-while-loop –
다음을 사용하여 제안하십시오 :'select ()'에 타임 아웃 값을 지정하면'select()'를 호출 할 때 오류가 발생했는지, 시간 초과로 인한 것인지 아니면 stdin이 데이터로 준비되어 있는지 확인하십시오. 그것이 있기 때문에 별도의 스레드에 배치하십시오. – user3629249