Skip to content

Instantly share code, notes, and snippets.

@JasonThomasData
Last active February 9, 2018 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JasonThomasData/8b6a7ac7761742e191bf492be0f171ef to your computer and use it in GitHub Desktop.
Save JasonThomasData/8b6a7ac7761742e191bf492be0f171ef to your computer and use it in GitHub Desktop.
Linux terminal program will let you enter keys without pressing `enter`
/* 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