Is there a simple, cross-platform way to get a single keystroke in D2 using Phobos?
For instance, a \"Press any key to continue...\" prompt, or a Brainfuck interpre
The simplest solution that works with D2 on Windows:
import std.stdio : writefln;
extern(C) int kbhit();
extern(C) int getch();
void main()
{
while(!kbhit())
{
// keep polling
// might use Thread.Sleep here to avoid taxing the cpu.
}
writefln("Key hit was %s.", cast(char)getch());
}
It might even work with D1, but I haven't tried it out.
Here's a Linux version, modified from Walter's post:
import std.stdio : writefln;
import std.c.stdio;
import std.c.linux.termios;
extern(C) void cfmakeraw(termios *termios_p);
void main()
{
termios ostate; /* saved tty state */
termios nstate; /* values for editor mode */
// Open stdin in raw mode
/* Adjust output channel */
tcgetattr(1, &ostate); /* save old state */
tcgetattr(1, &nstate); /* get base of new state */
cfmakeraw(&nstate);
tcsetattr(1, TCSADRAIN, &nstate); /* set mode */
// Read characters in raw mode
writefln("The key hit is %s", cast(char)fgetc(stdin));
// Close
tcsetattr(1, TCSADRAIN, &ostate); // return to original mode
}