The right way to Convert a String to an Integer in C


If you must convert a String to an Integer in C, then you are able to do one of many following:

Possibility 1 – Use atoi()

int atoi(const char *str);

You are able to do one thing like this:

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

int essential (void) {
    int worth;
    char str[20];
    strcpy(str,"123");
    worth = atoi(str);
    printf("String worth = %s, Int worth = %dn", str, worth);

    return(0);
}

Possibility 2 – Use strtol()

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

You are able to do one thing like this:

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

int essential(void) {
    char str[10];
    char *ptr;
    lengthy worth;
    strcpy(str, " 123");
    worth = strtol(str, &ptr, 10);
    printf("decimal %ldn", worth);

    return 0;
}

Possibility 3 – Use strtoumax()

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

You are able to do one thing like this:

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

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

    return 0;
}

Leave a Reply