How to Convert a String to an Integer in C


If you need to convert a String to an Integer in C, then you can do one of the following:

Option 1 – Use atoi()

int atoi(const char *str);

You can do something like this:

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

int main (void) {
    int value;
    char str[20];
    strcpy(str,"123");
    value = atoi(str);
    printf("String value = %s, Int value = %d\n", str, value);

    return(0);
}

Option 2 – Use strtol()

long int strtol(const char *string, char **laststr,int basenumber);

You can do something like this:

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

int main(void) {
    char str[10];
    char *ptr;
    long value;
    strcpy(str, " 123");
    value = strtol(str, &ptr, 10);
    printf("decimal %ld\n", value);

    return 0;
}

Option 3 – Use strtoumax()

uintmax_t strtoumax(const char* string, char** last, int basenumber);

You can do something like this:

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

int main(void) {
    char str[10];
    char *ptr;
    int value;
    strcpy(str, " 123");
    printf("The integer value:%d",strtoumax(str, &ptr,10));   

    return 0;
}