Convert Char to Int

How to Convert Char to Int in C++ (8 Programs)

BeginnerTopic: Advanced Number Programs
Back

C++ Convert Char to Int Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    char ch = '5';
    
    // Method 1: Direct subtraction
    int num1 = ch - '0';
    
    // Method 2: Using static_cast
    int num2 = static_cast<int>(ch) - 48;
    
    // Method 3: Using ASCII value
    int num3 = ch - 48;
    
    cout << "Character: " << ch << endl;
    cout << "Integer (method 1): " << num1 << endl;
    cout << "Integer (method 2): " << num2 << endl;
    cout << "Integer (method 3): " << num3 << endl;
    
    return 0;
}
Output
Character: 5
Integer (method 1): 5
Integer (method 2): 5
Integer (method 3): 5

Understanding Convert Char to Int

This program demonstrates 8 different methods to convert a character digit to an integer: subtracting '0', using static_cast, using ASCII value (48), using atoi(), using stringstream, using sscanf(), using stoi(), and manual conversion.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents