How To Convert A String To An Integer In C?

C programming language provides the string and integer types in order to store text and numbers. String type consists of single or more characters where integers consist of only numbers and can be used for mathematical operations and operators. While working with different types of data we may require to convert a string into an integer in order to make the mathematical calculation.

Convert String To Integer with atoi() Method

The standard method to convert string to integer in C is atoi() which is provided via the <stdlib.h> library. The atoi() method neglects the white spaces and converts the remaining characters to the integer and stops conversion when reaches a non-number character. The syntax of the atoi() method is very simple where it only accepts a constant character point that points single or more characters which is a string.

int atoi(const char *str);
  • *STR is a pointer to the character.

In the following example, we will convert clean strings into integers.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void) 
{
    int number;
    char str[10] = "2021";

    number= atoi(str);
    printf("String value = %s, Int value = %d\n", str, number);

    return(0);
}
String value=2021, Int value=2021

The string maybe not be in a clean state where it may contain non-number characters like whitespaces, alphabetic characters, etc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void) 
{
    int number;
    char str[10] = "   2021abc";

    number= atoi(str);
    printf("String value = %s, Int value = %d\n", str, number);

    return(0);
}
String value= 2021abc, Int value=2021

Convert String To Integer with strtol() Method

The strtol() method is another string to integer conversion method where the provided string is converted into the long integer. The same rules apply to atoi() method. The strtol() method syntax is like below where it accepts 3 parameters.

long int strtol(const char *string, char **laststr,int basenumber);
  • *string is the string or characters array we want to convert to integer or long integer.
  • **laststr is the stop character where the convertion will stop.
  • basenumber where decimal, octal or hexadecimal presentation can be used.

In the following example, we will convert the provided string into a long integer.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char str[10];
    char *p;
    long number;
    strcpy(str, " 2021");
    number= strtol(str, &p, 10);
    printf("Decimal %ld\n", number);

    return 0;
}

Leave a Comment