The way to Convert a String to an Integer in C

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

Choice 1 – Use atoi()#

int atoi(const char *str);

You are able to do one thing like this:

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

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

    return(0);
}

Choice 2 – Use strtol()#

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

You are able to do one thing like this:

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

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

    return 0;
}

Choice 3 – Use strtoumax()#

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

You are able to do one thing like this:

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

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

    return 0;
}