How do I read one character from stdin? (getc in C)
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Nov 14 12:05:42 PST 2015
On Saturday, 14 November 2015 at 13:33:49 UTC, Fer22f wrote:
> Anyone that has more experience can point me into a solution
> that is not deprecated? I haven't even researched about the
> deprecated options but looked into all free available D books I
> could find and I only found ways to get entire lines (even if
> it's just one character I still need to press enter).
That's because the operating system buffers it and needs to be
turned off. The getc in stdio.h works the same way, though if you
had a getch in conio.h or something like that, it is different.
You might be able to pull that from D, but since it isn't
technically standard C, it isn't available on all systems.
Notably, it is pretty common on Windows, but requires an add-on
library like ncurses on Linux. (which is commonly installed, but
not automatically linked)
Well, bottom line is you need a fair chunk of code to do this
(well, like 20 lines for minimal functionality, it isn't that bad
but still a bit involved), whether written yourself or pulled
from a library.
You might try taking my terminal library:
https://github.com/adamdruppe/arsd/blob/master/terminal.d
Download that file and add it to your build like this:
dmd yourfile.d terminal.d
Example usage:
import terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto input = RealTimeConsoleInput(&terminal,
ConsoleInputFlags.raw);
terminal.writeln("Press any key to exit.");
input.getch();
terminal.writeln("Bye!");
}
The first two lines have the library do various setup tasks like
turning off line buffering.
Once those two are set though the next three lines are pretty
ordinary and should work like you want.
It is kinda a pain to pass these to functions... you'd want to do
pass them around as pointers. Their destructors reset the
terminal to its default state so your program exits cleanly.
More information about the Digitalmars-d-learn
mailing list