HOWTO · C

How to Convert a String to Integer in C

This article introduces different methods in C to convert a string into an integer

On this page

Converting a C string to an integer depends on the input you accept and the checks your program needs. The standard library provides atoi(), strtol(), and strtoumax(). Use atoi() only when input is already trusted; for input that may be malformed or outside the destination type’s range, prefer a checked conversion with strtol() or strtoumax().

Using atoi() to Convert a String to an Integer in C

atoi() from <stdlib.h> skips leading whitespace, reads an optional sign and decimal digits, then stops at the first character that is not part of the number. It returns an int, but its interface does not report where parsing stopped or distinguish a valid zero from a failed conversion. If the converted value cannot be represented as an int, behavior is undefined. Use it only when the input format and range are guaranteed by other means.

Run this example:

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

int main(void) {
    const char *input = "123";
    int value = atoi(input);
    printf("%s -> %d\n", input, value);
    return 0;
}

Observed output:

123 -> 123

Using strtol() to Convert a String to an Integer in C

strtol() is declared in <stdlib.h> and returns a long. It accepts a base from 2 through 36; base 10 reads decimal, while base 0 recognizes the usual C integer prefixes. It skips leading whitespace and stops at the first character that does not belong to the number. Pass an end-pointer address to find that position. If the end pointer still points to the input’s first character, no digits were converted; if it points to a non-null character after conversion, the input has a trailing suffix.

Set errno to zero before calling strtol(). A result equal to LONG_MIN or LONG_MAX together with errno == ERANGE indicates that the value was outside the long range. If the destination is int, also check against INT_MIN and INT_MAX before casting. This complete example accepts only a whole decimal value that fits in an int:

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *input = "123";
    char *end;
    errno = 0;
    long parsed = strtol(input, &end, 10);

    if (end == input || *end != '\0' || errno == ERANGE ||
        parsed < INT_MIN || parsed > INT_MAX) {
        puts("conversion failed");
        return 0;
    }

    printf("value=%d\n", (int)parsed);
    return 0;
}

Observed output:

value=123

In production code, decide whether surrounding whitespace or a trailing suffix should be accepted; strtol() itself permits leading whitespace, and the end-pointer check above rejects any suffix after the digits.

Using strtoumax() to Convert a String to an Integer in C

strtoumax() is declared in <inttypes.h> and converts to uintmax_t, the widest unsigned integer type provided by the implementation. Like strtol(), it takes an end pointer and a base, and reports range overflow through errno == ERANGE after errno has been cleared. Include <stdint.h> for the uintmax_t type and <inttypes.h> for the function and PRIuMAX formatting macro.

An unsigned conversion can accept a leading minus sign and produce an unsigned result according to the function’s rules. If the application requires nonnegative input, reject a minus sign explicitly. The example below also requires at least one digit, rejects trailing characters, and prints the value using its matching format macro:

#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *input = "123";
    const char *sign = input;
    while (isspace((unsigned char)*sign)) {
        ++sign;
    }

    if (*sign == '-') {
        puts("conversion failed");
        return 0;
    }

    char *end;
    errno = 0;
    uintmax_t value = strtoumax(input, &end, 10);
    if (end == input || *end != '\0' || errno == ERANGE) {
        puts("conversion failed");
        return 0;
    }

    printf("value=%" PRIuMAX "\n", value);
    return 0;
}

Observed output:

value=123

The result type is unsigned and may be wider than int; check the value against the destination type’s maximum before converting it to a narrower type.

Choosing a C String-to-Integer Function

Choose atoi() when the input is trusted and fits in int, and the program does not need to distinguish malformed input from zero. For user input, files, or other data that may not follow the expected format, strtol() is generally the better signed conversion because its end pointer and errno support validation. Check both the long range and the range of any narrower destination type.

Choose strtoumax() for a nonnegative quantity that may exceed long’s positive range. Validate that digits were consumed, reject trailing text when the whole string must be numeric, check ERANGE, and enforce any narrower application-specific limit. Neither checked function decides what your application considers acceptable: the caller must define whether to allow whitespace, signs, prefixes, or trailing characters, then verify those rules before using the result.