Skip to main content

A replacement for atoi (or atol)

The atoi function has a serious flaw: it "does not detect errors", see man 3 atoi. Same with its siblings atol, atoll, atoq. Recently I played with different replacements for atol, the long-producing version of atoi: one based on strtol, the other on sscanf. The following is what I came up with. Replacement using strtol:

#include <stdlib.h>
int str_to_long__strtol(const char * text, long * output) {
    if (! text) return 0;
    char * end;
    long number = strtol(text, &end, 10);
    if (end != text) {
        *output = number;
        return 1;
    }
    return 0;
}

Replacement using sscanf:

#include <stdio.h>
int str_to_long__sscanf(const char * text, long * output) {
    if (! text) return 0;
    long number;
    int count = sscanf(text, "%ld", &number);
    if (count == 1) {
        *output = number;
        return 1;
    }
    return 0;
}

Both of these two functions deliver behavior equivalent to atol on these inputs:

  • "0002"
  • "2"
  • "2Hallo"
  • "+2"
  • " 2"

However, they differ to atol in two aspects:

  • No crash on input NULL
  • No success on input ""

Please note that all of these functions happily turn "2Hallo" into integer 2 with no complaints. The code above is public domain.