Convert char to int in C++

In this article, we will discuss how to convert a character to an integer in C or C++.

Table of Contents

Convert a char to an ascii int value

If we directly cast a char to an integer, then the integer will contain the ascii value of the character i.e.

#include <iostream>

int main()
{
    char ch = '6';

    // Convert character to integer
    int num = ch;

    std::cout << num <<std::endl;

    return 0;
}

Output:

54

We directly casted a char ‘6’ to an int. Therefore the int contains the ascii value of character ‘6’ i.e. 54. What if we want to convert a char to an actual int value instead of the ascii value?

Convert char to actual int using Typecasting

Suppose a character contains a digit i.e. ‘X’ and we want to convert it to an integer with value X only, not the ascii value. For example, if char contains ‘6’, then the converted int value should also be 6. Let’s see how to do that,

#include <iostream>

int main()
{
    char ch = '6';

    // Check if character is digit or not
    if (isdigit(ch))
    {
        // Convert character to integer
        int num = ch - '0';

        std::cout << num <<std::endl;
    }   
    return 0;
}

Output:

54

We first checked, if the character contains a digit or not. If yes, then minus the ascii value of character ‘0’ from it and it will give us the actual integer value.

Convert char to actual int using stringstream

In C++, the stringstream object is a kind of stream, in which we can insert integers, characters, floats etc. and in the end we can fetch a string object from the stringstream. It is also an easiest way to convert other data types to string values in C++. We can convert a char to string first and then use the stoi() to convert the string to an integer. For example,

#include <iostream>
#include <sstream>

int main()
{
    char ch = '6';

    // Create a String Stream 
    std::stringstream strm;
    // Insert character the in stream
    strm << ch;
    // Fetch the string from stream and convert to int
    int num = std::stoi(strm.str());

    std::cout << num <<std::endl;

    return 0;
}

Output

6

We first converted the character ‘6’ to a string object using the stringstream. Then we passed this string to the stoi() function, which interprets the string contents as an integral number of base 10 by default and returns the same value an int.

Summary:

We learned different ways to convert a char to an int in C++ i.e. either by typecasting or by using the stringstream.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top