Home »
C solved programs
Convert String to Integer in C programming language
In this C program, we are going to learn how to convert a string to the integer using different methods like direct, with using function and without using function?
Submitted by IncludeHelp, on May 27, 2016
Given a number as string and we have to convert it to integer using C program.
Example:
Input: "1234" (string value)
Output: 1234 (Integer value)
Code to Convert String to Integer in C programming
Direct Method
#include <stdio.h>
int main()
{
unsigned char text[]="1234";
int intValue;
intValue=((text[0]-0x30)*1000)+((text[1]-0x30)*100)+((text[2]-0x30)*10)+((text[3]-0x30));
printf("Integer value is: %d",intValue);
}
Output
Integer value is: 1234
Using atoi Function
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned char text[]="1234";
int intValue;
intValue=atoi(text);
printf("Integer value is: %d",intValue);
return 0;
}
Output
Integer value is: 1234
Using sscanf Function
#include <stdio.h>
int main()
{
unsigned char text[]="1234";
int intValue;
sscanf(text,"%04d",&intValue);
printf("Integer value is: %d",intValue);
return 0;
}
Output
Integer value is: 1234