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;
}
            
Input: A
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;
}
            
Input: z
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;
}
            
Input: B
Output: ASCII value of B is 66
Strings

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

Check whether a character is a vowel or consonant: C C++ Java Python

Check whether a character is an alphabet or not: C C++ Java Python

Find the ASCII value of a character: C C++ Java Python

Length of the string without using strlen() function: C C++ Java Python

Toggle each character in a string: C C++ Java Python

Count the number of vowels: C C++ Java Python

Remove the vowels from a string: C C++ Java Python

Check if the given string is Palindrome or not: C C++ Java Python

Print the given string in reverse order: C C++ Java Python

Remove all characters from string except alphabets: C C++ Java Python

Remove spaces from a string: C C++ Java Python

Replace a sub-string in a string: C C++ Java Python

Count common sub-sequences in two strings: C C++ Java Python

Compare two strings with wildcard support in one of them: C C++ Java Python

List all permutations of a given string in dictionary order: C C++ Java Python

Operations on Strings: C C++ Java Python