Disclaimer: It seems to work with gcc on Linux, but for some reason it does not work with VC ++ on Windows. The specifications seem to provide a lot of scope for implementation here, and VC ++ definitely uses it ...
Several functions are available on either std::basic_istream or its base std::basic_streambuf .
To find out if there is any character to enter, you can call in_avail in std::basic_streambuf :
if (std::cin.rdbuf() and std::cin.rdbuf()->in_avail() >= 0) { }
in_avail gives you the number of characters available without blocking, it returns -1 if there is no such character. After that, you can use the usual "formatted" read operations, such as std::cin >> input .
Otherwise, for unformatted reads, you can use readsome from std::basic_istream , which returns up to N characters available without blocking:
size_t const BufferSize = 512; char buffer[BufferSize]; if (std::cin.readsome(buffer, BufferSize) >= 1) { }
However, it is noted that the implementation of this method is greatly changed, so for a portable program this may not be so useful.
Note: as noted in the comment, the in_avail approach may be spotty. I confirm that it can work , however first you need to use the unclear feature of IO C ++ streams: std::ios_base::sync_with_stdio(false) , which allows C ++ streams to buffer input (and thus steal it from buffers C stdio).
source share