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,235
  • 1
  • 13
  • 24
  • 2
    Possible duplicate of [Non-blocking console input C++](http://stackoverflow.com/questions/6171132/non-blocking-console-input-c) – Pierre Apr 05 '16 at 09:34
  • 3
    in_avail doesn't do what you want. There is no way to do what you want using only the standard C++ library *unless* you are willing to deal with multiple threads. – n. m. could be an AI Apr 05 '16 at 09:36
  • @n.m can you explain a bit why doesn't in_avail do what i want in this case? – Biruk Abebe Apr 05 '16 at 09:47
  • 1
    in_avail deals with the *buffer* (the "buf" in streambuf). It tels you how much of it is filled by the input data but not consumed yet. The buffer is not filled by magic, it is filled by invoking a read operation. This operation would block. – n. m. could be an AI Apr 05 '16 at 09:52
  • @n.m Thanks. got it. – Biruk Abebe Apr 05 '16 at 09:58

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,921
  • 22
  • 31