-->





Translate

Cpp tutorial detecting a keypress and ASCII code

6 comments
Write a simple cpp program which detects a key pressed and its ASCII value with out pressing enter key and using cin>> on press ESC key program should exit. When user press a key its ASCII value should be displayed instantly. You can use any Cpp compiler CodeBlocks Recommended.

Concept used
  • Char and int data types
  • while infinite loop
  • conio.h header file getch() function
Program Logic and Explanation
  •  Its a simple program which reads a character of char data type
  • A header file conio.h is included to use getch() function
  • An infinite while loop breaks on pressing ESC key
  • In while loop  when program runs getch() function calls which wait to get character when we enter a character it store is ASCII value in int variable then displays the pressed key and its ASCII value on screen and then wait to another input a character.
This kind of program help user in game programming and programmer can control the value of any keypress by using a simple if statement. e.g you are making a game and want to control your inpute on pressing up, down, right, left, arrow keys simply get their ASCII values, use a control structure and control your input.
                          Value
Up Key               72
Down Key          80
Right Key          77
Left Key             75


Cpp code: Compiler used CodeBlocks Cpp Compiler

  1. #include<iostream>
  2. #include<conio.h>
  3. using namespace std;
  4. int main()
  5. {
  6.     char key_press;
  7.     int ascii_value;
  8.     cout<<"\n\t\t\tPress Any Key To Check  Its ASCI Value\n\n\t\t\tPress ESC to EXIT\n\n\n";
  9.     while(1)
  10.     {
  11.     key_press=getch();
  12.     ascii_value=key_press;
  13.     if(ascii_value==27) // For ESC
  14.      break;
  15.    cout<<"\t\t\tKEY Pressed-> \" "<<key_press<<" \" Ascii Value =  "<<ascii_value<<"\n\n";
  16.     }
  17.     return 0;
  18. }
Sample input outputs
Detecting a keypress in Cpp code

Its a simple program which helps the beginner to control input keys.

6 comments:

  1. No idea why, but getch() does not exist, but std::getchar() does.

    ReplyDelete
  2. The conio.h header is Windows-specific. It is not part of the standard and is not portable.

    ReplyDelete