ADVERTISEMENT
ADVERTISEMENT

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.