Non-blocking getch(), ncurses

The curses library is a package deal. You can’t just pull out one routine and hope for the best without properly initializing the library. Here’s a code that correctly blocks on getch(): #include <curses.h> int main(void) { initscr(); timeout(-1); int c = getch(); endwin(); printf (“%d %c\n”, c, c); return 0; }

Why getch() returns before press any key?

On Linux, getch() is probably the curses function, which is quite different from the Windows-specific function of the same name. curses (ncurses) is probably overkill for what you want to do. The simplest approach would be to wait until the user presses Enter, which you can do like this: int c; printf(“Press <enter> to quit: … Read more

Why getch() returns before press any key?

On Linux, getch() is probably the curses function, which is quite different from the Windows-specific function of the same name. curses (ncurses) is probably overkill for what you want to do. The simplest approach would be to wait until the user presses Enter, which you can do like this: int c; printf(“Press <enter> to quit: … Read more

Equivalent function to C’s “_getch()” in Java?

You could use the JLine library’s ConsoleReader.readVirtualKey() method. See http://jline.sourceforge.net/apidocs/jline/ConsoleReader.html#readVirtualKey(). If you don’t want to use a 3rd party library, and if you are on Mac OS X or UNIX, you can just take advantage of the same trick that JLine uses to be able to read individual characters: just execute the command “stty -icanon … Read more

How to implement getch() function of C in Linux?

Try this conio.h file: #include <termios.h> #include <unistd.h> #include <stdio.h> /* reads from keypress, doesn’t echo */ int getch(void) { struct termios oldattr, newattr; int ch; tcgetattr( STDIN_FILENO, &oldattr ); newattr = oldattr; newattr.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newattr ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldattr ); return ch; … Read more

Using kbhit() and getch() on Linux

If your linux has no conio.h that supports kbhit() you can look here for Morgan Mattews’s code to provide kbhit() functionality in a way compatible with any POSIX compliant system. As the trick desactivate buffering at termios level, it should also solve the getchar() issue as demonstrated here.