tags:

views:

230

answers:

2

Hi, is there any way to check if there is something in cin? I tryied peek() but if there isn't anything peek() waits for input and that isn't what I want. Thank you

+4  A: 

C++ streams and streambufs are synchronous, that is they block until there is enough input to read. There is no portable way to check a stream asynchronously. Consider calling peek() from a separate thread.

Vijay Mathew
+5  A: 

You cannot use cin to read keystrokes, and then go on to do something else if there is nothing available, which I think is what you may want. cin is a buffered stream and simply does not work in that way. In fact, there is no way of doing this using Standard C++ - you will have to use OS specific features.

anon
Thanks guys for your answers.
There is nothing we can do
I think Standard allows `cin` implementation which goes into EOF state if no input awaits. However standard libraries of compilers I know (which includes MS VS, Borland and GCC) do not provide such implementation. (I am not sure because I don't know if stream can stop being in EOF state by itself and this is what `cin` would have to do upon keystroke.)
Adam Badura
The eof state is the result of a read failing - it won't be set unless you do a read.
anon
Yes. So you call for example `std::cin.peek()` and if there are no keystrokes in the buffer it returns `traits_type::eof` instead of awaiting for keystrokes. (I know it doesn't but I think it might.) It must be doable because if you rebind standard input stream to a file for example (upon executing program) the `cin` will correctly get into EOF state upon file end.
Adam Badura