Detecting Which key is pressed and its ASCII value in C++

This C++ tutorial is about how to detect which key is pressed on the keyboard and find its ASCII value. Well, this is a very interesting topic and it requires prior knowledge of ASCII values.

What are the ASCII values?

ASCII is an abbreviation for American Standard Code for Information Interchange. This is an encoding standard that represents 128 English characters as numbers ranging from 0 to 127. These characters include all uppercase English alphabets, all lowercase English alphabets, digits from 0 to 9 and some special characters. Every ASCII value points to a single character. For example, ASCII value for ‘A’ is 65 and for ‘a’ is 97.

Also read: Deletion of any Non-ASCII characters present in C++

How to find which key is pressed and its ASCII value in C++

The program to detect a pressed key is very simple. All we have to do is to store the pressed key’s value in a character variable as it would be a character. Then we will print the value of that variable using cout. To find the ASCII value of that character we will first declare an integer variable and assign the value of the character variable to that integer variable as you can see in the program code below. Thus, we assign the ASCII value of that character in the integer variable. Now we can print that integer.

Detect Key Pressed and its ASCII value in C++

#include <iostream>
using namespace std;
int main()
{
  char a;
  cout << "Enter any key." << endl;
  cin >> a;
  cout << "you have pressed: \'" << a << "\'" << endl << endl;
  int b;
  b=a;
  cout << "ASCII value of the key pressed is: " << b;
  return 0;
}

Therefore, the output of the program would be like this.

Enter any key.
p
you have pressed: 'p'

ASCII value of the key pressed is: 112

In this example code, is a character variable and b is an integer variable. After printing the character variable a, we assign its value to b, which should hold an integer. In this way, the ASCII value of the given character is assigned to b.

Leave a Reply

Your email address will not be published. Required fields are marked *