C Program For Char to Int Conversion
There are 3 ways to convert the char to int in C language as follows:
- Using Typecasting
- Using sscanf()
- Using atoi()
Let’s discuss each of these methods in detail.
1. Using Typecasting
Method 1:
- Declare and initialize our character to be converted.
- Typecast the character to convert character to int using int.
- Print the integer using printf.
Example:
C
// C program demonstrating conversion of// char to int using typecasting#include <stdio.h>// Driver codeint main(){ char ch = 'G'; printf("%d", (int)(ch)); return 0;} |
Output
71
Method 2:
- Declare and initialize our character to be converted.
- Declare another variable as int N and assign the character ch to the N.
- Print the integer using printf.
Example:
C
// C program to demonstrate conversion of// char to int using typecasting#include <stdio.h>// Driver codeint 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 codeint 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 codeint 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 codeint main(){ char ch = 'g'; int N = (int)(ch)+0; printf("%d", N); return 0;} |
Output
103


