2430 : Introduction to Programming in C

Real time key-press

Some of you, for example those who are doing pong or snake, might be interested in having your program react to key-presses in real-time, and not waiting for the user to press Enter every time a key is input. The example program below may help in this:
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>

int main() {
        int ch;

        initscr();
        cbreak();
        noecho();
        refresh();
        ch = getch();
        while (ch != 'q') {
                system("clear");
                if (ch == 'a')
                        printf("Left arrow pressed\n\r");
                if (ch == 'd')
                        printf("Right arrow pressed\n\r");
                if (ch == 'w')
                        printf("Up arrow pressed\n\r");
                if (ch == 's')
                        printf("Down arrow pressed\n\r");
                refresh();
                ch = getch();
        }
        printf("Program terminated.\n\r");
        return 0;
}
When you run this program, you basically have the keys w, a, s, d as up, left, down, right. When you press one of those keys, it prints the corresponding message. When you press q, it quits.
Some things to pay attention to when doing this:
  1. If you use the simpio.h and/or random.h, remember to include those after you include curses.h. Otherwise you will get a compiler error having to do with bool.
  2. If you simply use getch() without any of the stuff near the top (like initscr(), cbreak(), noecho(), it's most likely going to crash with a segmentation fault.
  3. When you do all this, every time you print something to screen, it's not going to immediately display to the screen. It only displays everything at once when you do a refresh(). This basically refreshes the screen.
  4. When you are doing all this, if you want to print a line break, you will have to do \n\r instead of just \n. This is because the computer is at a pretty raw mode when you do this, therefore a line break \n is only going to move to the next line but not move back to the most left side of the line. \r will do this for you.
  5. Lastly, when you compile a program that includes curses.h, you have to put the -lcurses flag on your gcc line. For example:
    gcc myprogram.c -o myprogram.out -lcurses