Mike Meyer said:
That doesn't do what he wants, because it doesn't return until you hit
a newline.
Well, but that's true as well for getchar() (at least in many cases of
interactive input and line buffering), so in that respect I do think
it's a fairly direct replacement, depending on how the OP was going to
use getchar() in the application.
For example, compare: with:
main() ... c = sys.stdin.read(1)
{ ... print ord(c),
while (1) { ...
int ch = getchar();
printf("%d ",ch);
}
}
When run, both produce (at least for me):
0123456789 (hit Enter here)
48 49 50 51 52 53 54 55 56 57 10
under both Unix (at least FreeBSD/Linux in my quick tests) and Windows
(whether MSVC or Cygwin/gcc).
(I don't include any output buffer flushing, since it shouldn't be
needed on an interactive terminal, but you could add that to ensure
that it isn't the output part that is being buffered - I did try it
just to be sure on the Unix side)
The answer is system dependent. Or you can use massive overkill and
get curses, but if you're on windows you'll have to use a third party
curses package, and maybe wrap it
If you want to guarantee you'll get the next console character without
any waiting under Windows there's an msvcrt module that contains
functions like kbhit() and getch[e] that would probably serve.
-- David