i want to make a program in c++ , such that if the right arrow key is pressed 1 is displayed else
if left arrow key is pressed 0 is displayed.

please give me the code to do so and explain too.

Recommended Answers

All 3 Replies

To do that you have to get down to the nitty-gritty with the operating system. The curses library (*nix) or ncurses (MS-Windows) will make that easier for you. For MS-Windows there are several other options depending on the compiler you are using.

if your developing for windows and don't wanna go download some extra libraries and things then you can use the Win32 API. It give's you all the stuff you need to do this, just if your a beginner it might be a little complex.

Chris

It can be quite complex, but with the help of google, I managed to put this together as an example :)

#include <windows.h>
#include <iostream>
using namespace std;

void KeyEventProc(KEY_EVENT_RECORD); 

int main()  { 
  HANDLE hStdin; 
  DWORD cNumRead; 
  INPUT_RECORD irInBuf[128]; 

  hStdin = GetStdHandle( STD_INPUT_HANDLE ); 

  if ( hStdin == INVALID_HANDLE_VALUE ) 
    return 0;

  while ( true )  { 

    if (! ReadConsoleInput( hStdin, irInBuf, 128, &cNumRead) )
      return 0;

    for (DWORD i = 0; i < cNumRead; i++)  {
      if ( irInBuf[i].EventType == KEY_EVENT ) {
        KeyEventProc( irInBuf[i].Event.KeyEvent );
      }
    }
  } 

  return 0; 
}

void KeyEventProc(KEY_EVENT_RECORD ker) {
  if (ker.bKeyDown == false) { // Only if key is released
    switch ( ker.wVirtualKeyCode ) {
      case VK_LEFT:   cout << "Left\n";   break;
      case VK_RIGHT:  cout << "Right\n";  break;
      case VK_UP:     cout << "Up\n";     break;
      case VK_DOWN:   cout << "Down\n";   break;
    }
  }
}

Hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.