Convert char to int in C and C++

Learn convert char to int in c and c++ with practical examples, diagrams, and best practices. Covers c++, c, gcc development techniques with visual explanations.

Converting char to int in C and C++

Hero image for Convert char to int in C and C++

Learn the various methods to safely and effectively convert character representations of digits to their integer equivalents in C and C++.

Converting a char to an int is a common task in C and C++ programming, especially when dealing with input that is read character by character, such as from a file or standard input. It's crucial to understand that a char type in C/C++ stores an ASCII (or other character encoding) value, not the numerical value it might visually represent. For instance, the character '5' is stored as its ASCII value (which is 53), not the integer 5.

Understanding Character Representation

Before diving into conversion methods, it's important to grasp how characters are stored. In C and C++, a char is an integer type that is typically 1 byte in size. When you declare char c = '5';, the variable c does not hold the integer 5. Instead, it holds the ASCII value corresponding to the character '5', which is 53. Similarly, '0' corresponds to 48, '1' to 49, and so on. This sequential ordering of digit characters in ASCII (and other common encodings like UTF-8) is key to simple conversion techniques.

flowchart TD
    A["Input: char '5'"] --> B{"ASCII Value?"}
    B -->|Yes| C["Stores 53 (decimal)"]
    B -->|No| D["Stores 0x35 (hex)"]
    C --> E["Not the integer 5"]
    D --> E
    E --> F["Requires Conversion"]

Representation of a character digit's ASCII value

Method 1: Subtracting the ASCII Value of '0'

The most common and idiomatic way to convert a character digit to its integer equivalent is by subtracting the ASCII value of the character '0'. Because digit characters '0' through '9' are guaranteed to be contiguous in the ASCII table (and other widely used character sets), subtracting '0' from any digit character will yield its numerical value. For example, '5' - '0' evaluates to 53 - 48 = 5.

#include <iostream>

int main() {
    char digit_char = '7';
    int digit_int = digit_char - '0';

    std::cout << "Character: " << digit_char << std::endl;
    std::cout << "Integer value: " << digit_int << std::endl;

    // Example with a non-digit character (will produce unexpected results)
    char non_digit_char = 'A';
    int non_digit_int = non_digit_char - '0';
    std::cout << "Non-digit char 'A' converted: " << non_digit_int << std::endl;

    return 0;
}

Converting a character digit to an integer using subtraction.

Method 2: Using std::stoi (C++11 and later)

For C++11 and newer, the std::stoi function (string to integer) provides a robust way to convert a string representation of a number to an integer. While it's typically used for std::string, you can easily convert a single char to a std::string or use a char array (C-style string) with it. This method offers error handling capabilities, which can be beneficial for more complex scenarios.

#include <iostream>
#include <string>
#include <stdexcept>

int main() {
    char digit_char = '9';
    std::string s(1, digit_char); // Convert char to std::string

    try {
        int digit_int = std::stoi(s);
        std::cout << "Character: " << digit_char << std::endl;
        std::cout << "Integer value (stoi): " << digit_int << std::endl;
    } catch (const std::invalid_argument& ia) {
        std::cerr << "Invalid argument: " << ia.what() << std::endl;
    } catch (const std::out_of_range& oor) {
        std::cerr << "Out of range: " << oor.what() << std::endl;
    }

    // Example with a non-digit character
    char non_digit_char = 'X';
    std::string s_non_digit(1, non_digit_char);
    try {
        int non_digit_int = std::stoi(s_non_digit);
        std::cout << "Non-digit char 'X' converted: " << non_digit_int << std::endl;
    } catch (const std::invalid_argument& ia) {
        std::cerr << "Invalid argument for 'X': " << ia.what() << std::endl;
    }

    return 0;
}

Using std::stoi for character to integer conversion with error handling.

Method 3: Using atoi or sscanf (C-style functions)

For C-style programming or compatibility, functions like atoi (ASCII to integer) or sscanf can be used. These functions operate on C-style strings (char*). Similar to std::stoi, they are more geared towards converting multi-digit numbers but can be adapted for single characters.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char digit_char = '4';
    char str[2]; // C-style string to hold the character and null terminator
    str[0] = digit_char;
    str[1] = '\0';

    int digit_int_atoi = atoi(str);
    printf("Character: %c\n", digit_char);
    printf("Integer value (atoi): %d\n", digit_int_atoi);

    // Using sscanf
    int digit_int_sscanf;
    sscanf(str, "%d", &digit_int_sscanf);
    printf("Integer value (sscanf): %d\n", digit_int_sscanf);

    return 0;
}

Converting a character digit to an integer using atoi and sscanf.

Validation Before Conversion

Regardless of the method chosen, it's good practice to validate that the char actually represents a digit before attempting conversion. This prevents unexpected behavior or errors, especially when dealing with user input or external data. The isdigit() function from <cctype> (C++) or <ctype.h> (C) is ideal for this.

#include <iostream>
#include <cctype> // For isdigit

int main() {
    char input_char = '5';

    if (std::isdigit(input_char)) {
        int digit_int = input_char - '0';
        std::cout << "'" << input_char << "' is a digit. Converted to: " << digit_int << std::endl;
    } else {
        std::cout << "'" << input_char << "' is NOT a digit." << std::endl;
    }

    input_char = 'K';
    if (std::isdigit(input_char)) {
        int digit_int = input_char - '0';
        std::cout << "'" << input_char << "' is a digit. Converted to: " << digit_int << std::endl;
    } else {
        std::cout << "'" << input_char << "' is NOT a digit." << std::endl;
    }

    return 0;
}

Validating a character using isdigit() before conversion.