Convert int to char in C++

In this tutorial, we will learn how to convert int to char in C++ in an easy way.

Introduction

An integer is a whole number that can be either positive, negative, or zero. On the other hand, Characters are simple alphabets like A, B, C… It can also be special symbols like $,+,%, etc.

What is ASCII?

Before moving ahead, Let me give you an understanding of ASCII. As we already know that computers can only understand numbers. So an ASCII code is the numerical representation of characters that can be letters or some special symbols such as $ and %.

Conversion of int to char in C++

We will convert our int to char in 3 easy steps:-

  1.  Declaration and initialization:- Firstly we will declare and initialize our integer with a value that we want to convert.

 

int i=83;

If you don’t want to initialize an integer with a random value.  You can also take input from the user, this can be done by using a cin statement.

 

int i;
cout<<"Enter an integer"<<endl;
cin>>i;

2. Typecasting:-

It is a method of converting one data type to another. Here we are typecasting the integer i and storing its value in c which is of datatype char.

char c=char(i);

3. Printing the character:-

At last, we will print the character corresponding to the  integer using the cout statement.

cout<<"The character corresponding to the integer is : "<<c<<endl;

Entire code

#include <iostream>
using namespace std;

int main()
{

    //convert int to char in c++

    int i=83;  //variable declaration and initialization
   
    char c=char(i); // cast conversion

    cout<<"The character is : "<<c<<endl; //printing the char

    return 0;

Output:-

The character is : S

That’s it for this tutorial I hope it might be helpful for you.

Thank you!

Leave a Reply

Your email address will not be published.