Skip to content

Instantly share code, notes, and snippets.

@physacco
Created November 8, 2016 07:15
Show Gist options
  • Save physacco/5aed1c3a31ce7932c1b9461e979203de to your computer and use it in GitHub Desktop.
Save physacco/5aed1c3a31ce7932c1b9461e979203de to your computer and use it in GitHub Desktop.
Get char from stdin without pressing enter.
#include <stdio.h>
#include <termios.h>
int getch(void) {
int ch;
struct termios oldt;
struct termios newt;
tcgetattr(STDIN_FILENO, &oldt); /*store old settings */
newt = oldt; /* copy old settings to new settings */
newt.c_lflag &= ~(ICANON | ECHO); /* make one change to old settings in new settings */
tcsetattr(STDIN_FILENO, TCSANOW, &newt); /*apply the new settings immediatly */
ch = getchar(); /* standard getchar call */
tcsetattr(STDIN_FILENO, TCSANOW, &oldt); /*reapply the old settings */
return ch; /*return received char */
}
int main() {
while (1) {
int ch = getch();
printf("Get char: %d\n", ch);
}
return 0;
}
// Tested on Ubuntu 14.04
// Refer to: http://www.cplusplus.com/forum/unices/18395/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment