Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting arrow keys from cin

Tags:

c++

cin

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++?

like image 395
Baruch Avatar asked Dec 08 '11 18:12

Baruch


2 Answers

Here is a pointer if you dont mind using getch() located in 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;
}
like image 60
Software_Designer Avatar answered Sep 22 '22 00:09

Software_Designer


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.

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

Graphic-application frameworks such as SDL, Allegro, Irrlicht or Ogre3D come with full keyboard and mouse handling, too.

like image 35
Kerrek SB Avatar answered Sep 18 '22 00:09

Kerrek SB