I need to detect a keystroke, without the user pressing enter. What's the most elegant way?
I.e. If the user hits the letter Q, without pressing enter, the program does something.
I need to detect a keystroke, without the user pressing enter. What's the most elegant way?
I.e. If the user hits the letter Q, without pressing enter, the program does something.
Theres no good way to do this portably, as far as I know, other than to use a library like ncurses
, which provides the getch(void)
function.
Note: It appears getchar(void)
from stdio.h
waits until the enter key is pressed then feeds your the characters,s o it won't work.
In Windows <conio.h>
provides funtion _getch(void)
which can be used to read keystroke without echo-ing them (print them yourself if you want).
#include <conio.h>
#include <stdio.h>
int main( void )
{
int ch;
puts( "Type '@' to exit : " );
do
{
ch = _getch();
_putch( ch );
} while( ch != '@' );
_putch( '\r' ); // Carriage return
_putch( '\n' ); // Line feed
}
In unix/posix, the standard way of doing this is to put the input into non-canonical mode with tcsetattr:
#include <termios.h>
#include <unistd.h>
:
struct termios attr;
tcgetattr(0, &attr);
attr.c_lflag &= ~ICANON;
tcsetattr(0, TCSANOW, &attr);
See the termios(3) man page for more details (and probably more information than you wanted to know).