I don't know about Windows (where apparently _getch()
is the way to go) but on UNIXes you can set the standard input stream (file descriptor 0
) into non-canonical mode using tcgetattr()
and tcsetattr()
to get the key immediately. To suppress the key presses from showing up, you'll need to also disable echoing:
termios old_tio, new_tio;
int rc = tcgetattr(0,&old_tio);
new_tio=old_tio;
new_tio.c_lflag &=(~ICANON & ~ECHO);
rc = tcsetattr(0,TCSANOW,&new_tio);
std::string value;
if (std::cin >> value) {
std::cout << "value='" << value << "'\n";
}
rc = tcsetattr(0,TCSANOW,&old_tio);
This code
- first gets the current state of the terminal flags
- clears the
ICANON
and ECHO
flags
- read hidden input (in this case a string but it can be an individual key, too)
- restores the original settings
There is, unfortunately, no portable way of dealing with these setting, i.e., you will need to resort to platform specific uses. I think the use of tcgetattr()
and tcsetattr()
is applicable to POSIX systems, though.