Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scanf() time

Status
Not open for further replies.

isaisa

Programmer
May 14, 2002
97
0
0
IN
Hi,
I wanted to restrict the input time for the scanf(). If the user does not enter with in say 2 minutes, the scanf() call should be terminated. Is it possible to acheive ?

I am using windows flavours for testing this .... please suggest ...

Thanks
sanjay
 
You can't do that on scanf level (stdio stream). No timing on this C run-time library level.
 
What if you create a new thread to call scanf() and then kill the thread after x amount of time?
 
I'm afraid that it's a dangerous op to kill a thread waiting in console i/o RTL routine.
Here is a sketch of a possible (but not a complete;) Windows solution:
Code:
/* Modified from the MSDN clock() fn description. */
/* Pauses for a specified number of milliseconds. */
void sleep( clock_t wait )
{
   clock_t goal;
   goal = wait + clock();
   while( goal > clock() && !_kbhit())
      ;
}

/* Flush keyboard buffer */
void KbFlush()
{
  while (_kbhit())
    getch();
}

bool isClockOK()
{
  clock_t t = clock();
  return t != (clock_t)-1;
}

static int GetT(clock_t msec = 0)
{
  int c = 0;
  sleep(msec);
  if (_kbhit())
  {
    c = _getche();
  }
  return c;
}
/* Console string input with timeout. Busy wait loop! */
char* tgets(char* line, int n, int timeoutms)
{
  int c, k = 0;
  if (!line || n <= 0)
     return 0;

  --n;	/* reserve a room for zero terminator */

  while (k < n)
  {
    c = GetT(timeoutms);
    if (c)
    {
       if (c == '\n' || c == '\r') /* Enter pressed */
          break;
       line[k++] = c;
    }
    else /* Time out */
    {
      line[k] = '\0';
      return 0;
    }
  }

  line[k] = 0;
  return line;
}
...
char line[80];

if (tgets(line,sizeof line, 1000*60*2)) /* 2 minuts */
{
   /* Process input line with sscanf */
}
else /* Time out! */
It's a dirty solution (busy wait loop) but it works. There are some problems with OEM console input and CR/LF echo - try to adopt this code if you wish...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top