Find the ASCII value of a character in C++
Understanding ASCII Values
ASCII (American Standard Code for Information Interchange) assigns numerical values to characters. For example, 'A' has an ASCII value of 65.
We will explore three different methods to find the ASCII value of a character in C++.
Method 1: Using Direct Conversion
This method prints the ASCII value of a character using type casting.
#include <iostream> using namespace std; int main() { char ch; cout << "Enter a character: "; cin >> ch; cout << "ASCII value of " << ch << " is " << int(ch); return 0; }
Output: ASCII value of A is 65
Method 2: Using a Function
This method uses a function to return the ASCII value of a character.
#include <iostream> using namespace std; int getASCII(char ch) { return int(ch); } int main() { char ch; cout << "Enter a character: "; cin >> ch; cout << "ASCII value of " << ch << " is " << getASCII(ch); return 0; }
Output: ASCII value of z is 122
Method 3: Using Pointers
This method finds the ASCII value using a pointer to the character.
#include <iostream> using namespace std; int main() { char ch; cout << "Enter a character: "; cin >> ch; char *ptr = &ch; cout << "ASCII value of " << *ptr << " is " << int(*ptr); return 0; }
Output: ASCII value of B is 66