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;
}
Don’t use
atoi(), or any of theatoi*()functions, if you care about error handling. These functions provide no way of detecting errors; neitheratoi(99999999999999999999)noratoi("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 witherrnoto get full checking.)If you just want an int value, you can use
strtol()(which, after error checking, gives you alongresult) and convert it tointafter also checking that the result is in the representable range ofint(seeINT_MINandINT_MAXin<limits.h>).strtoul()gives you anunsigned longresult.strtoll()andstrtoull() are forlong longandunsigned long longrespectively; they’re new in C99, and yourcompilerimplementation might not support them (though most non-Microsoft implementations probably do).