Is there a way to read input directly from the key

2019-01-26 22:49发布

This question already has an answer here:

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

3条回答
一纸荒年 Trace。
2楼-- · 2019-01-26 23:26

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.

查看更多
神经病院院长
3楼-- · 2019-01-26 23:27

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.

查看更多
时光不老,我们不散
4楼-- · 2019-01-26 23:28

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>.

查看更多
登录 后发表回答