This question already has an answer here:
-
Capture characters from standard input without waiting for enter to be pressed
15 answers
And I know there's std::cin
, but that requires the user to enter a string, then press ENTER. Is there a way to simply get the next key that is pushed without needing to press ENTER to confirm
You can use
#include <conio.h>
and then catch char with cases such as this
char c;
if (_kbhit())
{
c = getch();
switch(c)
{
case ‘\0H’ :
cout << "up arrow key!" << endl;
break;
}
}
Beware: I have not tried it... and remember to put the whole thing into a "while(true)" to test.
What you're looking for is related to manipulating the console, and is OS-dependent. If you're in a UNIX-based OS, check out the curses library, and in Windows, there are getch()
and kbhit()
functions from <conio.h>
.
It looks like the most upvoted answer is a bit outdated.
The ncurses library (based on the mentioned curses library) is a portable implementation available for unix and linux based operating systems, windows and others.
It supports a wide variety of terminal interfaces.