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.

getch and arrow codes

By pressing one arrow key getch will push three values into the buffer: ‘\033’ ‘[‘ ‘A’, ‘B’, ‘C’ or ‘D’ So the code will be something like this: if (getch() == ‘\033’) { // if the first value is esc getch(); // skip the [ switch(getch()) { // the real value case ‘A’: // code … Read more

What is the equivalent to getch() & getche() in Linux?

#include <unistd.h> #include <termios.h> char getch(void) { char buf = 0; struct termios old = {0}; fflush(stdout); if(tcgetattr(0, &old) < 0) perror(“tcsetattr()”); old.c_lflag &= ~ICANON; old.c_lflag &= ~ECHO; old.c_cc[VMIN] = 1; old.c_cc[VTIME] = 0; if(tcsetattr(0, TCSANOW, &old) < 0) perror(“tcsetattr ICANON”); if(read(0, &buf, 1) < 0) perror(“read()”); old.c_lflag |= ICANON; old.c_lflag |= ECHO; if(tcsetattr(0, TCSADRAIN, … Read more