tags:

views:

122

answers:

3

How do i get an input from keyboard, without pressing 'return' in C / Mac Os

+4  A: 

On Unix-like systems with terminals (I suppose that MacOS X qualifies), then you need to set the terminal to so-called "cbreak" mode. The point is that the terminal is keeping the data until "return" is pressed, so that there is nothing your C code can do, unless it instructs the terminal not to do such buffering. This is often called "cbreak mode" and involves the tcsetattr() function.

A bit of googling found this code which seems fine. Once the terminal is in cbreak mode, you will be able to read data as it comes with standard getchar() or fgetc() calls.

Thomas Pornin
It's also possible to force "line so far" by typing Ctrl-D (and when done on an empty line, this results in 0 character s being readable, this then signals an end-of-file condition).
Vatine
+2  A: 

If you have to handle the details yourself, use a curses variant. If it is available, prefer "ncurses" over "curses". Note that some keys are "Meta" keys which really just modify the base key codes. There are several "modes" for reading key input, which range from "cooked", through "partially cooked", to "raw". Each mode has its own peculiarities, read the documentation carefully.

Sometimes it's better to use existing key handling code from various game programming libraries, I've heard of some good results using SDL's key scanning loops. That was a while back, so perhaps newer (and better) toolkits exist.

Edwin Buck