Basic keyboard input

Because it cannot assume much about the environment in which it will be run, ANSI C provides no mechanism for unbuffered, direct keyboard input (i.e. it cannot retrieve a single character, and cannot interpret cursor keys or other non-character keys). This makes handling interactive input somewhat difficult. ncurses provides some platform specific methods of doing this.

This program simply accepts keypresses from the user and immediately prints the hexadecimal key code, and a textual description of the key pressed.

Programming Issues

After initialisation, the program calls noecho() to prevent the key being echoed to the screen, and keypad() to enable the cursor and other keys to be detected by the program. The getch() function is then used to retrieve each character at a time, until the user hits 'q'.

In our intprtkey() function, we return a string describing the key pressed. If the key was a printable character, we just return a pointer to a string containing that character only. Otherwise, we use an array of structs to hold the key code of a selection of other keys (as defined in <curses.h>) along with their short descriptions.

Usage

Link with the ncurses library. The ncurses "Hello, World!" example includes details on how to do this.

Source and Downloads