Reputation:
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;
}
Upvotes: 5
Views: 13348
Reputation: 263237
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).
Upvotes: 9
Reputation: 738
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
Upvotes: 0
Reputation: 43508
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.
Upvotes: 7