Alf P. Steinbach wrote:
* Rolf Magnus: Alf P. Steinbach wrote:
> * DiegoC:
>> How can I know if any character has been typed without using the kbhit
>> of <conio.h>. The function should not block the program.
>
> This is not covered by the standard language or library; use other
> libraries (e.g. your operating system's API).
Well, there is std::cin.rdbuf()->in_avail() tocheck how many characters
are available for reading,
AFAIK in_avail() is not required to check lower level buffers.
And when it does not, relying on it to check for interactive keypresses
may cause an infinite loop.
Or other bad things; I've not bothered to check out the finer details
of the modern iostreams since they're not usable for serious work (in
particular, reading anything but pure text has Undefined Behavior since
the conversion defers to sscanf which has UB for nonconforming input,
but to not scare newbies needlessly I don't usually mention that...).
but it's not guaranteed to work correctly on all implementations.
Nothing is guaranteed to work correctly on all implementations, but
everything is guaranteed to work correctly on correct implementations.
If it's not a correct implementation, it's not an implementation ;-)
What I meant by "work correctly" is "do what the OP wants".
Correct does not in this case, AFAICS, extend to provide the OP's
functionality.
Is there something I may have overlooked?
That's what Stroustrup has to say about it in TC++PL:
<quote>
A call to in_avail() is used to see how many characters are available in the
buffer. This can be used to avoid waiting for input. When reading from a
stream connected to a keyboard, cin.get(c) might wait until the user comes
back from lunch. On some systems and for some applications, it can be
worthwile taking that into account when reading. For example:
if (cin.rdbuf()->in_avail()) { // get() will not block
cin.get(c);
// do something
}
else { // get() might block
// do something else
}
Note that some systems, it can be hard to determine if input is available.
Thus, in_avail() might be (poorly) implemented to return 0 in cases where
an input operation would succeed.
</quote>
This pretty much means that you are right in that using in_avail() might
result in an endless loop that never reads input, because in_avail() always
returns 0.