Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Getch/Getchar

Part of TutorialFundamentals

Description

Get a character from the keyboard.

Example

import std.c.stdio;
import std.stdio;

void main() {
    char k;

    writefln("\nI'm going to ask you to press 10 keys (I promise it's painless).\n"
    "Certain keys don't count, but the whole alphabet is fair game.\n");

    for(int i = 0; i < 10; i++) {
        version(Windows) {
            writef("Press key: %d\t", i);
            k = getch();
        }
        version(linux) {
            writef("Press key (follow with return): %d\t", i);
            k = cast(char) getchar();
        }
        version(OSX) {
            // Unfortunately, merely using getchar() does not disable stdin and readline buffering.
            writef("Press key (follow with return): %d\t", i);
            k = cast(char) getchar();
        }
        writef("[%s]\t", k);    /* print the character pressed */

        writefln("[%d]\n", k);  /* print ASCII code for key */

        char enter = cast(char) getchar();

    }
    writefln("\nThe End.\n");
}

Source

Based on getch.html by jcc7.

Modified 2012-04-28 by thaumaturgist: example now works in D2 using DMD.

Attachments

  • hello.d (0.9 kB) -example source, added by thaumaturgist on 04/28/12 14:50:29.
  • example.d (0.9 kB) -example source, added by thaumaturgist on 04/28/12 14:51:30.