Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My goal is that i will ask a user a question and say i will provide 10 seconds to answer that question.If the user exits the given time then the program terminates. But even though the time has been exceeded, i cant seem to terminate the program. Basically what i mean is that the program still keeps waiting for the user's input.
I cant understand how to fix this error. Please any suggestions! Thanks

C++
#include<iostream>
#include <ctime>
#include<stdlib.h>
#include <conio.h>
#include <string>
#include <Windows.h>

using namespace std;

int main()
{
time_t begin,end;
bool flag = true;
string ch;

begin = time(NULL);
while(flag)
{
  end = time(NULL);
  
  if(difftime(end,begin)<30)
   {
    cout<<"Enter your answer"<<endl;
    getline(cin,ch);
   }

  if(difftime(end,begin)>30)
   {
    flag = false;
    cout<<"Sorry you are timed out"<<endl;
   }
}

system("pause");
}
Posted
Comments
enhzflep 24-Nov-14 1:16am    
Insert a return; statement after the message that tells the user they timed out. After-all, main is just a function. As with any function, you can exit it by reaching the closing brace, or by simply using return.

1 solution

My suggestion would be a redesign.

1. your main-code belongs in a separate thread function.
2. in your (new) main function you start thread and wait up to 10 sec (maybe 100 waits of 100 ms Sleep) and check for the input. The input buffer must be global!!!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900