Find the ASCII Value of a Character

C++C++Beginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/BasicsGroup -.-> cpp/variables("Variables") cpp/BasicsGroup -.-> cpp/strings("Strings") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/variables -.-> lab-96136{{"Find the ASCII Value of a Character"}} cpp/strings -.-> lab-96136{{"Find the ASCII Value of a Character"}} cpp/output -.-> lab-96136{{"Find the ASCII Value of a Character"}} cpp/user_input -.-> lab-96136{{"Find the ASCII Value of a Character"}} cpp/files -.-> lab-96136{{"Find the ASCII Value of a Character"}} cpp/code_formatting -.-> lab-96136{{"Find the ASCII Value of a Character"}} end

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 LabEx :-)\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 LabEx :-)


===== 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.