How to Get Timed Input using cin

Hi,

I am trying to get the input like option from the user using cin but if the user is not responding for some time I want to use the default value which does not need users interaction can any one help to do this in unix c++?

int main()
{
char sex = 'M' ;
cout << "Are you Male/Female (M/F)?" << flush ;
cin >> setw(1) >> sex ; // Here I don't want to wait indefinatily

switch(sex)
{
case 'F' :
// do something
break ;
default :
case 'M' :
// do something
break ;
}

retrurn 0 ;
}

Thanks In advance.
Balasubramnaian

Hi,

I am trying to get the input like option from the user using cin but if the user is not responding for some time I want to use the default value which does not need users interaction can any one help to do this in unix c++?

int main()
{
char sex = 'M' ;
cout << "Are you Male/Female (M/F)?" << flush ;
cin >> setw(1) >> sex ; // Here I don't want to wait indefinatily wait for
// some 20 seconds for the user input if he is not
// provided the input by that time use default

switch(sex)
{
case 'F' :
// do something
break ;
default :
case 'M' :
// do something
break ;
}

retrurn 0 ;
}

Thanks In advance.
Balasubramnaian

see non blocking read() help, you can do with that

Thanks for your reply I will try to do that.

Sample Application to implement timed read

#include <sys/time.h>

int main()
{
   fd_set fdset;
   struct timeval timeout;
   int  rc;
   int  val;

   timeout.tv_sec = 6;   /* wait for 6 seconds for data */
   timeout.tv_usec = 0;


   FD_ZERO(&fdset);

   FD_SET(0, &fdset);

   rc = select(1, &fdset, NULL, NULL, &timeout);
   if (rc == -1)  /* select failed */
   {
       printf("ERROR path\n");
       val='E';
   }
   else if (rc == 0)  /* select timed out */
   {
       printf("DEFAULT path\n");
       val='D';
   }
   else 
   {
      if (FD_ISSET(0, &fdset)) 
      {
         val = getchar();
      }
   }
   printf("VAL is %c\n", val);
}

WoW! Cool!!! It works Thanks for your help.