Reading one character from stdin to D

The documentation std.stdio

does not display a function read

that can be used to get one character from standard input, only readln

to get a string. std.file

has a function read

, but it requires a filename which is not available on standard input as far as I know.

How to read one character from stdin

?

+3


source to share


1 answer


Several options, depending on what you need:

If you just want a character for programming, but don't mind buffering it with a string:

  • Use rawRead

    or byChunk

    to buffer its block ( stdin

    is an instance std.stdio.File

    , so all methods from this http://dlang.org/phobos/std_stdio.html available to it) and read one element from that array at the same time.

  • Use a C function fgetc

    on import core.stdc.stdio;

    and use C stdin instead of a D wrapper. They are both compatible with each other, so reading from one will not mess up the buffering of the other.

  • Use a function readf

    to capture one piece of data at a time.



All of these options will work for your program, but you will notice that the user will still have to hit the enter key until the program does anything, because the main input stream is buffered to one full line at a time. This can also be changed:

If you need one key at once, for things like interactive sessions with a user:

  • See CyberShadow link in comment

  • Disable line buffering when calling the operating system. This means, tcsetattr

    on Posix and SetConsoleMode

    on Windows - search the web for details on how to turn off line buffering in C, and the same code can be easily translated to D. Also see the source on my terminal.d that does this: https: //github.com/adamdruppe/arsd/blob/master/terminal.d#L1078

  • Just use a library like my terminal.d which provides a framework to change the buffering mode for you and functions like getch

    and kbhit

    similar to the old one conio.h

    in the link. Here's a sample file: http://arsdnet.net/dcode/book/chapter_12/07/input.d which shows a simple "press any key to continue" example.

  • Use a more functional C library, for example ncurses

    from D. http://code.dlang.org/packages/ncurses If you've ever used it from C it's pretty much the same.

+4


source







All Articles