4

I want to see which key is pressed by user.

I know there is cin() or getline(cin, var) but I don't want an input, I want to get the number of the key(index, or code it is called?).

For instance, I want to get if the user has pressed F1 or F10 or Enter or Escape and then in return do something proper.

For instance:

if(user_has_pressed_escape)
{
 exit_the_console();
}
Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105

4 Answers4

6

This is available via the OS own API. Different OSes have different APIs (for instance android does not have a F10 key at all).

Often you will use a third party library to wrap the API so you can code independent from the OS. There are a lot of choices when it comes to a 3rd party library: SDL, QT, wxWidgets, GTK and many many more..

These libraries hide the interaction with the specific OS API from you and let you code once and run on many types of systems. But to understand how it works under the hood you might look at each OS documentation.

For instance on Windows GetKeyboardState or PeekMessage

On Linux X11: XQueryKeymap or via XPeekEvent

odedsh
  • 2,594
  • 17
  • 17
  • You mean C++ has no built in library for this purpose? – Mostafa Talebi Jul 02 '14 at 13:17
  • No. There is no ISO C++ library to accomplish this. Each OS has a way to do it, though. Windows has RAW I/O. Linux (and probably OS X) has a file in /dev. I can only guess about other OSes. Of course, I am assuming that you want scan codes. Still, same applies for just getting when a key is pressed. – Graznarak Jul 02 '14 at 15:53
  • this is where if you want portable code, you'll want to separate the business logic from the user interface – iedoc Jul 03 '14 at 13:19
3

You can easily get event of ESC key down using ASCII table https://en.wikipedia.org/wiki/ASCII

if (27 == getchar()) // 27 is for ESC
{
    //do something
}

Function keys (F1, F2, ...) depend on your OS.

Brunisboy
  • 123
  • 1
  • 19
Dakorn
  • 883
  • 6
  • 11
1

According to the "INPUT VALUES" section of the "PDCurses User's Guide" found at http://pdcurses.sourceforge.net/doc/PDCurses.txt, the getch function can be used to detect such keys if keypad has been enabled.

Here are the relevant key codes.

KEY_F0      function keys; space for 64 keys is reserved
KEY_F(n)    (KEY_F0+(n))
KEY_EXIT    Exit key

The PDCurses library has the benefit of being cross platform.

Benilda Key
  • 2,836
  • 1
  • 22
  • 34
0

C++ as a C ancestor is strongly system-independent, so there are no ways to do what you want using only the language itself, or even STL library. You will have to use different libraries on different platforms. Typically that will be only OS-dependent, because most operating system is actually looking for keyboard actions, like pressing, using interruption mechanism. So your program will have to interact with OS strongly.

You should try avoid working with keyboard itself, if you do not know much about this topic.