简体   繁体   中英

atoi function in C not working properly

Can somebody explain why atoi function don't work with nuber who have more than 9 digits.
For example:

I entered 123456789, program says 123456789, but when i entered 12345678901 program say -519403114... Thanks for helping.

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;
}

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).

Because you are overflowing an int with such a large value.

Moreover, atoi is deprecated and thread-unsafe on many platforms, so you'd better ditch it in favour of strto(l|ll|ul|ull) .

Consider using strtoull instead. Since unsigned long long is a 64-bit type on most modern platforms, you'll be able to convert a number as big as 2 ^ 64 ( 18446744073709551616 ).

To print an unsigned long long , use the %llu format specifier.

if you are writing win32 application then you can use windows implementation of atoi, for details check the below page.

http://msdn.microsoft.com/en-us/library/czcad93k%28v=vs.80%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM