Convert char into int in C++ with examples

This tutorial will show how to convert char into int in C++. There are some simple approaches to convert a char into an int, let’s see each approach individually.

Example 1 –

#include<bits/stdc++.h>
using namespace std;

int main(){
    char a = 'k';
    char b = 'a';
    cout<<"ASCII value of k is: "<<int(a)<<endl;
    cout<<"ASCII value of k is: "<<int(b)<<endl;
    return 0;
}

Output – 

ASCII value of k is: 107
ASCII value of k is: 97

In this example, we saw that we can easily convert or get an integer value of char using typecasting. This is the best way to build a relationship or convert char into int or vice versa.

Example 2 –

#include<bits/stdc++.h>
using namespace std;

int main(){
    char a = 'a';
    char k = 'k';
    char z = 'Z';
    int num1 = a - 'a' + 1;
    int num2 = k - 'a' + 1;
    int num3 = z - 'A' + 1;
    cout<<"This character number is: "<<num1<<endl;
    cout<<"This character number is: "<<num2<<endl;
    cout<<"This character number is: "<<num3<<endl;
    return 0; 
}

Output – 

This character number is: 1
This character number is: 11
This character number is: 26

In this example, we saw that we don’t need to use typecasting because in this example we declared three int variables which is num1, num2 and num3. So compiler automatically detects that we have to store the integer value of the following characters (i.e. ASCII values). After assigning characters to that integer variable we have to subtract the ‘a’ character for lowercase characters and ‘A’ to get the character values of uppercase characters for example (a = 1, b = 2, c = 3, ……., z = 26). Remember we have to be careful with uppercase and lowercase characters because they have different ASCII values.

Leave a Reply

Your email address will not be published. Required fields are marked *