C++ 从cin获取方向键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8435923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting arrow keys from cin
提问by Baruch
I am sure this must have been asked before, but a quick search found nothing.
我相信这之前一定有人问过,但快速搜索一无所获。
How can I get the arrow/direction keys with cin
in c++?
如何cin
在 C++ 中获得箭头/方向键?
回答by Kerrek SB
It has indeed been asked before, and the answer is that you cannot do it.
以前确实有人问过,答案是你做不到。
C++ has no concept of a keyboard or a console. It only knows of an opaque input data stream.
C++ 没有键盘或控制台的概念。它只知道不透明的输入数据流。
Your physical console preprocesses and buffers your keyboard activity and only sends cooked data to the program, usually line-by-line. In order to talk to the keyboard directly, you require a platform-specific terminal handling library.
您的物理控制台会预处理和缓冲您的键盘活动,并且通常会逐行向程序发送经过处理的数据。为了直接与键盘对话,您需要一个特定于平台的终端处理库。
On Linux, this is usually done with the ncurses
or termcap
/terminfo
libraries. On Windows you can use pdcurses
, or perhaps the Windows API (though I'm not familiar with that aspect).
在 Linux 上,这通常使用ncurses
或termcap
/terminfo
库来完成。在 Windows 上,您可以使用pdcurses
,或者 Windows API(尽管我不熟悉这方面)。
Graphic-application frameworks such as SDL, Allegro, Irrlicht or Ogre3D come with full keyboard and mouse handling, too.
SDL、Allegro、Irrlicht 或 Ogre3D 等图形应用程序框架也带有完整的键盘和鼠标处理。
回答by Software_Designer
Here is a pointer if you dont mind using getch()
located in conio.h
.
如果您不介意使用getch()
位于conio.h
.
#include <stdio.h>
#include <conio.h>
#define KB_UP 72
#define KB_DOWN 80
#define KB_LEFT 75
#define KB_RIGHT 77
#define KB_ESCAPE 27
int main()
{
int KB_code=0;
while(KB_code != KB_ESCAPE )
{
if (kbhit())
{
KB_code = getch();
printf("KB_code = %i \n",KB_code);
switch (KB_code)
{
case KB_LEFT:
//Do something
break;
case KB_RIGHT:
//Do something
break;
case KB_UP:
//Do something
break;
case KB_DOWN:
//Do something
break;
}
}
}
return 0;
}