How to check if std::cin (or stdin) has data in it's buffer.

Hi guys,
I need to be able to check if an input buffer (in this case std::cin or stdin) has data that can be read without blocking the program. Meaning, I don't want the program to wait for input when checking. I simply just want it to check and if something is there, get the data, if not, move along. I need this for a little game I'm building where I need to check for keyboard input. Do I need to write my own function? Or does C++ STL provide one?
The only C++ function that comes close to what you're asking is std::cin.rdbuf()->in_avail():
http://www.cplusplus.com/reference/streambuf/streambuf/in_avail/

But it won't help you to do what you're describing: std::cin's buffer is not updated when the user presses a key. It is only updated when you, the programmer, attempt to make a read from std::cin and its buffer happens to be empty, so it has to ask the OS for input.

If you're trying to build a keyboard-interactive game, use a gaming library that provides such functionality, or the underlying OS API. (for POSIX OS, the API is select()/poll(), combined with appropriate tty driver settings)

Last edited on
hmmm..Ok. That makes this a little more tricky, but thank you for the help!
I was able to get what I wanted by just having my Qt framework call a CallBack function I provided. The function supplied the ASCII key value (or a custom code for non-ASCII keys) as one of it's arguments.
Topic archived. No new replies allowed.