Convert string to integer
Here we explain C program to convert string to an integer. String should consist of digits only and an optional ‘-‘ (minus) sign at the beginning for integers. For string containing other characters, we can stop conversion as soon as a non-digit character is encountered. But in our program, we will handle the ideal case when only valid characters are present in the string.
#include<stdio.h> int stringToInt(char[] ); int main(){ char str[10]; int intValue; printf("\n\t\t\t...Welcome To EduNews.Tech... "); printf("\n\nEnter any integer as a string: "); scanf("%s",str); intValue = stringToInt(str); //converting string value to integer type by making its function. printf("Equivalent integer value: %d",intValue); printf("\n\n\n\t\t\tThankyou for Joining Us !"); printf("\n\t\t\t\t!Regards EduNews !"); return 0; } int stringToInt(char str[]) //it is a function made to convert the string value to integer value. { int i=0,sum=0; while(str[i]!='\0') //string not equals to null { if(str[i]< 48 || str[i] > 57) // ascii value of numbers are between 48 and 57. { printf("Unable to convert it into integer.\n"); return 0; } else { sum = sum*10 + (str[i] - 48); i++; } } return sum; }
Program Output:
I hope this post helps you to understand the conversion of string to int without using library functions and its implementation in C programming language.
Keep coding 🙂