atoi function in C not working properly (when exceeding a certain value)

user997863 picture user997863 · Oct 16, 2011 · Viewed 11.6k times · Source

Might someone explain why the atoi function doesn't work for nmubers with more than 9 digits?

For example:

When I enter: 123456789, The program program returns: 123456789,

However,when I enter: 12345678901 the program returns: -519403114...

int main ()
{
    int i;
    char szinput [256];
    printf ("Enter a Card Number:");
    fgets(szinput,256,stdin);
    i=atoi(szinput);
    printf("%d\n",i);
    getch();
    return 0;
}

Answer

Keith Thompson picture Keith Thompson · Oct 16, 2011

Don't use atoi(), or any of the atoi*() functions, if you care about error handling. These functions provide no way of detecting errors; neither atoi(99999999999999999999) nor atoi("foo") has any way to tell you that there was a problem. (I think that one or both of those cases actually has undefined behavior, but I'd have to check to be sure.)

The strto*() functions are a little tricky to use, but they can reliably tell you whether a string represents a valid number, whether it's in range, and what its value is. (You have to deal with errno to get full checking.)

If you just want an int value, you can use strtol() (which, after error checking, gives you a long result) and convert it to int after also checking that the result is in the representable range of int (see INT_MIN and INT_MAX in <limits.h>). strtoul() gives you an unsigned long result. strtoll() and strtoull() are for long long and unsigned long long respectively; they're new in C99, and your compiler implementation might not support them (though most non-Microsoft implementations probably do).