The Wayback Machine - https://web.archive.org/web/20221006173506/https://www.geeksforgeeks.org/c-program-for-char-to-int-conversion/
Skip to content
Related Articles

Related Articles

C Program For Char to Int Conversion

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Aug, 2022
View Discussion
Improve Article
Save Article

There are 3 ways to convert the char to int in C language as follows:

  1. Using Typecasting
  2. Using sscanf()
  3. Using atoi()

Let’s discuss each of these methods in detail.

1. Using Typecasting

Method 1:

  1. Declare and initialize our character to be converted.
  2. Typecast the character to convert character to int using int.
  3. Print the integer using printf.

Example:

C




// C program demonstrating conversion of
// char to int using typecasting
#include <stdio.h>
 
// Driver code
int main()
{
    char ch = 'G';
    printf("%d", (int)(ch));
    return 0;
}

Output

71

Method 2:

  1. Declare and initialize our character to be converted.
  2. Declare another variable as int N and assign the character ch to the N. 
  3. Print the integer using printf.

Example:

C




// C program to demonstrate conversion of
// char to int using typecasting
#include <stdio.h>
 
// Driver code
int main()
{
    char ch = 'g';
    int N = (int)(ch);
    printf("%d", N);
    return 0;
}

Output

103

2. Using sscanf

Reads data from s and stores it in the places specified by the additional arguments in the parameter format. Below is the C program to convert char to int using sscanf.

Example:

C




// C program to demonstrate conversion of
// char to int using sscanf()
#include <stdio.h>
// Driver code
int main()
{
    const char* s = "136";
    int x;
    sscanf(s, "%d", &x;);
    printf("\nThe integer value of x is %d ", x);
    return 0;
}

Output

The integer value of x is 136 

3. Using atoi

If the execution is successful, the atoi() method returns the converted integer value. If the given string cannot be converted to an integer, it will return 0. Below is the C program to convert char to int using atoi()

Example:

C




// C program to demonstrate conversion of
// char to int using atoi()
#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
{
    const char* str = "136";
 
    int y = atoi(str);
    printf("\nThe integer value of y is %d", y);
    return 0;
}

Output

The integer value of y is 136

4. Converting char to int by adding 0 

C




#include <stdio.h>
   
// Driver code
int main()
{
    char ch = 'g';
    int N = (int)(ch)+0;
    printf("%d", N);
    return 0;
}

Output

103

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!