What is the difference between atol() & strtol()?
According to their man pages, they seem to have the same effect as well as matching arguments:
long atol(const char *nptr);
long int strtol(const char *nptr, char **endptr, int base);
In a generalized case, when I don’t want to use the base argument (I just have decimal numbers), which function should I use?
strtolprovides you with more flexibility, as it can actually tell you if the whole string was converted to an integer or not.atol, when unable to convert the string to a number (like inatol("help")), returns 0, which is indistinguishable fromatol("0"):Outputs:
strtolwill specify, using itsendptrargument, where the conversion failed.Outputs:
Therefore, for any serious programming, I definitely recommend using
strtol. It’s a bit more tricky to use but this has a good reason, as I explained above.atolmay be suitable only for very simple and controlled cases.