How to use kbhit and getch (C programming) [closed]
No need to explain, the code talks better : #include <conio.h> // … printf(“please press P key to pause \n “); int key = 0; while(1) { if (_kbhit()) { key =_getch(); if (key == ‘P’) break; } }
No need to explain, the code talks better : #include <conio.h> // … printf(“please press P key to pause \n “); int key = 0; while(1) { if (_kbhit()) { key =_getch(); if (key == ‘P’) break; } }
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
Figured it out by testing all the stuff by myself. Couldn’t find any topics about it tho, so I’ll just leave the solution here. This might not be the only or even the best solution, but it works for my purposes (within getch’s limits) and is better than nothing. Note: proper keyDown() which would recognize … Read more
Since ruby 2.0.0, there is a ‘io/console’ in the stdlib with this feature require ‘io/console’ STDIN.getch
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
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.
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
#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