1

I'm trying to make a game where objects move when certain keys have been pressed. But I want to implement it so that stuff is moving and loops are running all the time. So far the keyboard input functions such as scanf and getchar have all been waiting for me to press a key until they allow the program to continue. How do i listen for key presses without stalling the program (without using threads)?

VanGo
  • 199
  • 1
  • 11
  • This is covered in the C FAQ list: http://c-faq.com/osdep/readavail.html – Steve Summit Mar 11 '16 at 23:16
  • What Ben said. Or on unix clones, you can put the terminal into non-canonical mode ([see this answer](https://stackoverflow.com/a/29723614/3386109)). On MS systems, you can use `kbhit` to check for keyboard input, and `getch` to read the key. – user3386109 Mar 11 '16 at 23:17

1 Answers1

0

There is a way of implementing this using a loop.
The following program will do something else in a loop, and in every pass it will check if a key has been pressed. The pressed key will then be stored to a variable c.

#include <stdio.h>
#include <conio.h>

int main(void) {
    char c = '\0';

    while (1) { 
        if (kbhit()) { 
            c = getch(); 
        }
        /* If a key has been pressed */
        if (c != '\0') {
            /* Do something */
            c = '\0'; // and put it back to \0
        }

        /* Do something else */
    }

    return 0;
}

Note: This solution works only on Windows and other operating systems where the header file "conio.h" can be included

bobasti
  • 1,778
  • 1
  • 20
  • 28
  • kbhit() is not defined as part of the ANSI C standard. – Martin James Mar 11 '16 at 23:23
  • Efficient IO handling is what threads, (well, preemptive multitasking OS), are good at. – Martin James Mar 11 '16 at 23:34
  • I get the following error messages when I try to run this code. LINK ERROR: unresolved external symbol '_kbhit' in module 'square' of file 'square.obj' – VanGo Mar 11 '16 at 23:40
  • @VanGo What operating system are you using? – user3386109 Mar 11 '16 at 23:46
  • If you are using Linux, check out this [answer](http://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux) to see an example illustrating how ncurses could be used like the conio example. – bobasti Mar 11 '16 at 23:47