C Program to Convert String to Integer

In this C program, we will convert a string to integer using atoi function and using a user defined function. To convert string to integer, we first take a string as input from user using gets function. Input string should consist of digits('0' to '9') and minus sign('-') for negative numbers. It may contains some non-numerical characters like alphabet, but as soon as we see any non-numerical character we stop conversion and return converted integer till now.

For Example
Input String : "12345"
Output Integer : 12345

Input String : "-123abcd"
Output Integer : -123

C program to convert a string to integer using atoi function

atoi function is defined inside stdlib.h header file. Function atio converts the string parameter to an integer. If no valid conversion exist for that string then it returns zero. Here is the declaration for atoi() function.

int atoi(const char *str);
#include <stdio.h>
#include <stdlib.h>

int main(){
    char inputString[20];
    printf("Enter a String\n");
    gets(inputString);

    printf("Integer: %d \n", atoi(inputString));

    return 0;
}
Output
Enter a String
2014
Integer: 2014
Enter a String 
-2000abcd
Integer: -2000

C program to convert a string to integer without using atoi function

In this program we convert a string to integer without using atoi function. We first check that inputString[0] is '-' or not to identify negative numbers. Then we convert each numerical character('0' to '9') to equivalent digit and appends it to converted integer. Then we multiply converted integer with -1 or 1 based upon whether input string contains negative or positive number. Finally, it prints the integer on screen using printf function.


#include <stdio.h>

int main(){
    char inputString[20];
    int sign = 1, number = 0, index = 0;
    
    printf("Enter a String\n");
    gets(inputString);

    if(inputString[0] == '-'){
        sign = -1;
        index = 1;
    }
    
    while(inputString[index] != '\0'){
        if(inputString[index] >= '0' &&
            inputString[index] <= '9'){
            number = number*10 + inputString[index] - '0';
        } else {
            break;
        }
        index++;
    }

    number = number * sign;
    printf("String : %s \n", inputString);
    printf("Integer: %d \n", number);

    return 0;
}
Output
Enter a String for Integer conversion 
-24356
String : -24356
Integer: -24356

Related Topics
C program to swap two strings
C program to find a substring from a given string
C program to find length of string
C program to compare two strings
C program to check string is palindrome
C program to convert lowercase string to uppercase
C program to check if two strings are anagram
List of all C programs