0

I am trying to use the c++ standard input stream cin to get a user input without blocking the execution of the program. I have this code:

char ch;
int flag=1;

do
{
   if(cin.rdbuf()->in_avail())
   {
       cin.get(ch);
       flag=0;
   }
   else
       //do something else
}while(flag);

//do something with the input

The idea here is to wait for user input without blocking while doing something else and as soon as the user provides an input we process the input( all in one thread). I know from the documentation the streambuf class used by the input stream provides the in_avail() function which will return a non-zero values when ever there is input ready in the buffer. The code above is not working as i expected it and is looping forever even if i provide a keyboard input at some point. i am using MS visual studio 2005 in windows 7. what am i missing here?

Biruk Abebe
  • 2,194
  • 1
  • 11
  • 24

1 Answers1

2

The function in_avail does:

Returns the number of characters available in the get area.

The get area may be empty even if some characters are readable from the underlying operating system buffer.

You will trigger a refill of the get area when you effectively call a read operation on the streambuf. And that operation will block. The reason is that the method underflow which is responsible for filling the get area:

Ensures that at least one character is available in the input area

And to ensure this, it must block until some character is read.

fjardon
  • 7,758
  • 20
  • 30