Skip to content

Instantly share code, notes, and snippets.

@AlmuHS
Last active November 8, 2022 15:52
Show Gist options
  • Save AlmuHS/4dc6a74b7e7d409ac75138c3e857c252 to your computer and use it in GitHub Desktop.
Save AlmuHS/4dc6a74b7e7d409ac75138c3e857c252 to your computer and use it in GitHub Desktop.
getch() implementations for Windows and Linux, without conio.h or ncurses.h
#include <iostream>
#ifdef WIN32
#include <windows.h>
char getch(){
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT) & (~ENABLE_LINE_INPUT));
char data;
ReadFile(hStdin, &data, 1, NULL, nullptr);
return data;
}
#else
#include <unistd.h>
#include <termios.h>
char getch(){
termios TermConf;
tcgetattr(STDIN_FILENO, &TermConf);
TermConf.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &TermConf);
char data;
data = std::cin.get();
return data;
}
#endif // WIN32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment