Last active
February 9, 2018 11:13
-
-
Save JasonThomasData/8b6a7ac7761742e191bf492be0f171ef to your computer and use it in GitHub Desktop.
Linux terminal program will let you enter keys without pressing `enter`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* I took the code at www.flipcode.com/archives/_kbhit_for_linux.shtml and refactored it to suit my needs. | |
* Usually a terminal program will have an input buffer and will wait until it finds a carriage return (enter) to process the buffer. | |
* This code allows you to enter keys without pressing enter, and is useful for a robot project of mine (to give the robot instructions without pressing enter). | |
* | |
* This is tested and working on Linux (Arch, Mint) and Mac osx. | |
* | |
* g++ -std=c++14 key_press.cpp -o key_press | |
*/ | |
#include <iostream> | |
#include <unistd.h> | |
#include <termios.h> | |
#include <sys/ioctl.h> | |
int get_number_of_chars() | |
{ | |
static const int STDIN = 0; | |
int bytesWaiting; | |
ioctl(STDIN, FIONREAD, &bytesWaiting); | |
return bytesWaiting; | |
} | |
int prevent_wait_for_EOL() | |
{ | |
static const int STDIN = 0; | |
termios term; | |
tcgetattr(STDIN, &term); | |
term.c_lflag &= ~ICANON; | |
tcsetattr(STDIN, TCSANOW, &term); | |
} | |
int get_last_char_in_buffer(int number_chars_in_buffer) | |
{ | |
int ch; | |
while(number_chars_in_buffer > 0) | |
{ | |
ch = std::cin.get(); | |
number_chars_in_buffer = number_chars_in_buffer - 1; | |
} | |
return ch; | |
} | |
int main(int argc, char** argv) { | |
prevent_wait_for_EOL(); | |
while (true) { | |
usleep(1000000); | |
int number_chars_in_buffer = get_number_of_chars(); | |
if(number_chars_in_buffer > 0) | |
{ | |
int ch = get_last_char_in_buffer(number_chars_in_buffer); | |
std::cout<<"\nDo something with "<< ch<< std::endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment