strtol provides you with great flexibility, as it can really tell you whether the entire string has been converted to an integer or not. atol , when it is impossible to convert a string to a number (for example, to atol("help") ), returns 0, which is indistinguishable from atol("0") :
int main() { int res_help = atol("help"); int res_zero = atol("0"); printf("Got from help: %d, from zero: %d\n", res_help, res_zero); return 0; }
Outputs:
Got from help: 0, from zero: 0
strtol will indicate using the endptr argument where the conversion failed.
int main() { char* end; int res_help = strtol("help", &end, 10); if (!*end) printf("Converted successfully\n"); else printf("Conversion error, non-convertible part: %s", end); return 0; }
Outputs:
Conversion error, non-convertible part: help
Therefore, for any serious programming, I definitely recommend using strtol . This is a little more difficult to use, but it has a good reason, as I explained above.
atol may only be suitable for very simple and controlled cases.
Eli Bendersky Sep 25 '10 at 5:54 2010-09-25 05:54
source share