Find the ASCII Value of a Character

Beginner

Introduction

In this lab, you will learn how to find the ASCII value of a character in the C++ programming language. The concept of type-casting will be used to change the data type of the variable while accessing it.

Creating the C++ file

Open a terminal, and create a new file called main.cpp in the ~/project directory:

cd ~/project
touch main.cpp

Writing the code

Copy and paste the following code into the main.cpp file:

#include <iostream>

using namespace std;

int main()
{
    //variable declaration - a char variable takes a single character as input
    char c;

    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << "===== Program to Find the ASCII value of a character ===== \n\n";

    //take user input
    cout << "Enter a character : ";
    cin >> c;

    //printing the ASCII value of the entered character
    cout << "\nThe ASCII value of the entered character is : " << (int)c << "\n\n";

    return 0;
}

Compiling and running the code

To compile and run the code, run the following command in the terminal:

g++ main.cpp -o main && ./main

Test the code

The output should look like this:

Welcome to Studytonight :-)


===== Program to Find the ASCII value of a character =====

Enter a character : B

The ASCII value of the entered character is : 66

Summary

Congratulations! You have successfully created a C++ program that finds the ASCII value of a character. In this lab, you have learned about type-casting and how to change the data type of a variable while accessing it. Remember that the ASCII value of a character is unique and can be used in a variety of applications.

Other Tutorials you may like