C Language Strings Convert Strings to Number: atoi(), atof() (dangerous, don't use them)


Warning: The functions atoi, atol, atoll and atof are inherently unsafe, because: If the value of the result cannot be represented, the behavior is undefined. (7.20.1p1)

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

int main(int argc, char** argv)
    int val;
    if (argc < 2)
        printf("Usage: %s <integer>\n", argv[0]);
        return 0;

    val = atoi(argv[1]);

    printf("String value = %s, Int value = %d\n", argv[1], val);

    return 0;

When the string to be converted is a valid decimal integer that is in range, the function works:

$ ./atoi 100
String value = 100, Int value = 100
$ ./atoi 200
String value = 200, Int value = 200

For strings that start with a number, followed by something else, only the initial number is parsed:

$ ./atoi 0x200
$ ./atoi 0123x300

In all other cases, the behavior is undefined:

$ ./atoi hello
Formatting the hard disk...

Because of the ambiguities above and this undefined behavior, the atoi family of functions should never be used.

  • To convert to long int, use strtol() instead of atol().
  • To convert to double, use strtod() instead of atof().
  • To convert to long long int, use strtoll() instead of atoll().