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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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
0
$ ./atoi 0123x300
123

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().
C99
  • To convert to long long int, use strtoll() instead of atoll().


Got any C Language Question?