I'm trying to make a game that continues running until a key is pressed and then it should take that key in and do something with it then continue running as per normal. How do I do this?
I'm on MAC so even though I've come across a windows library called conio.h which can handle this using kbhit() and getch(), I can't get it working for me...
//
// main.c
// conioTesting
//
//
#include <stdio.h>
#include "myconio_mac.h"
int main(int argc, const char * argv[]) {
int counter = 0;
while (counter < 2) {
if (kbhit()) {
char key = getch();
printf("\n Key is %c \n", key);
printf("Keyboard hit detected \n");
} else {
printf("Nothing. \n");
}
}
printf("Passed!!!!!!!!!! \n");
}
On the MAC, you need to fiddle with the terminal settings to turn off line buffering. (You can also turn off echo.) Once the terminal is setup correctly, you can use
read
to get single characters from the keyboard.In the sample code below, the
kbsetup
function takes care of the terminal settings. Thegetkey
function checks for a key press, and returns the key if any, or'\0'
if no key was read. Themain
function has a loop that prints the time once per second, and prints any key that the user presses. Press'q'
to exit the program.Sounds like you want to wait for a key to be pressed and then continue execution:
Should be very simple to do with pthreads (need to compile:
gcc test.c -lpthread
).You could check out the answers mentioned on another stackoverflow post:
Problem with kbhit()[and getch()] for Linux