7

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

There is nothing we can do
  • 21,267
  • 27
  • 92
  • 184

2 Answers2

5

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.

  • 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 Dec 18 '09 at 13:06
  • 1
    The eof state is the result of a read failing - it won't be set unless you do a read. –  Dec 18 '09 at 13:18
  • 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 Dec 20 '09 at 09:03
4

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
  • 25,329
  • 3
  • 54
  • 90