Enter a key and display it's ascii value in c++
To display the ASCII value of a key in C++, you can use the static_cast
function to convert the key to its ASCII value. Here's an example code snippet that demonstrates this:
#include <iostream>
int main() {
char key;
std::cout << "Enter a key: ";
std::cin >> key;
int asciiValue = static_cast<int>(key);
std::cout << "ASCII value of " << key << " is " << asciiValue << std::endl;
return 0;
}
Explanation:
Include the
<iostream>
header file, which allows input and output operations.Declare a variable
key
of typechar
to store the key entered by the user.Prompt the user to enter a key using
std::cout << "Enter a key: ";
.Read the user input and store it in the
key
variable usingstd::cin >> key;
.Declare a variable
asciiValue
of typeint
to store the ASCII value of the key.Use the
static_cast<int>(key)
expression to convert thekey
fromchar
type toint
type, and assign the result toasciiValue
.Print the ASCII value of the key using
std::cout << "ASCII value of " << key << " is " << asciiValue << std::endl;
.Finally,
return 0;
to indicate successful execution of the program.
This code will take a key input from the user and display its corresponding ASCII value. The static_cast
function is used to explicitly convert the char
type to int
type in order to obtain the ASCII value.