Convert strings to numbers safely

suggest change

atoi, atol, atoll, and atof do not provide a useful way to distinguish invalid input from a valid zero. Integer overflow in the atoi family also has undefined behavior. Prefer the strto* functions, which report where conversion stopped and can report range errors.

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

int main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s INTEGER\n", argc > 0 ? argv[0] : "program");
        return EXIT_FAILURE;
    }

    errno = 0;
    char *end;
    long value = strtol(argv[1], &end, 10);

    if (end == argv[1] || *end != '\0') {
        fprintf(stderr, "Not an integer: %s\n", argv[1]);
        return EXIT_FAILURE;
    }
    if (errno == ERANGE) {
        fprintf(stderr, "Integer is outside the range of long: %s\n", argv[1]);
        return EXIT_FAILURE;
    }

    printf("%ld\n", value);
    return EXIT_SUCCESS;
}

The base argument controls accepted syntax. Base 10 accepts decimal input. Base 0 recognizes the standard prefixes for octal and hexadecimal, and recognizes binary prefixes where supported by the selected C version.

Use strtoul, strtoll, or strtoull for other integer result types, and strtof, strtod, or strtold for floating-point input. Validate any additional application-specific range after conversion.

The unsigned conversion functions accept an optional leading minus sign and apply unsigned negation. Reject the sign explicitly if negative text is not valid for the application.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents