How to Convert a String to an Integer in C

0 min read 157 words

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;
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags