String to int C conversion program – This program convert string to int value using atio(str) function. Also, it a custom function is included to check if all entered string contains only char digits.

Program Description:

This program accepts input string that contains only char digits from user and store into an array of characters. The array is passed to the converter function that returns corresponding converted integer value. Before passing array to converter function, the main () checks if entered string contains only char digits and no other chars. If the string contains other characters except char digits then it prompt user to enter string containing digits only.

String to int C Source code

/*C program to convert string to int*/
#include<stdio.h>

/* convert string to int number*/
int stringToIntConterver(char str[]){
	int num;
	//example : char arr[4] ={3,4,5,6}
	//convert char array to number using atoi function
	num = atoi(str);	

	return num;	
}

//you can write one liner statment also
//int stringToIntConterver(char str[]){
//	return atoi(str);;	
//}

//Check if string contains only char digits
int isStringContainsDigitsOnly(char str[]){

	int i;
	int flag = 1;
	for( i=0; i < strlen(str); ++i){
		if (!isdigit(str[i])){

			//if found other char except char digits
			//Break and return false
			flag = 0;
			break;
		} 
	}

	return flag;
}
int main(){

	int number;

	char str[32];

	printf("Enter a string containing digits: ");
	scanf("%s",str);	

	//Check if string contains digits only
	if(!isStringContainsDigitsOnly(str)){
		printf("Please enter string containing digits only ");
		return 0;
	}

	//All are char digits in strin. Convert string to int
	number = stringToIntConterver(str);

	printf("Integer value :%d",number);


	return 0;
}

Output:

Enter a string containing digits: 1234
Integer value :1234

Enter a string containing digits: 1234ab
Please enter string containing digits only

Enter a string containing digits: 4567789
Integer value :4567789

NOTE:

If you enter char digits string that contains out of integer range, then the output value will always be printed as 2147483647.
[The 32-bit int data type can hold integer values in the range of −2,147,483,648 to 2,147,483,647]

For example, see the output for below give string.

Enter a string containing digits: 1234455678990
Integer value :2147483647

Related Posts