strtol() Usage Guide

strtol() is what you get when you want to be flexible and yet have a simple interface. At the first glance it looks like a nice, clean function: you pass it a string and a base and you get the value and optionally a pointer to the rest of the string.

Then you read the documentation.

To convert const char *str to a long, properly checking for overflow, invalid trailing characters and empty input, it is necessary to do the following:

char *p;
errno = 0;
result = strtol(str, &p, base);
if (errno != 0 || *p != 0 || p == str)
  error_handling ();

It is necessary to check both errno and *p; if you don’t check errno, you get 0 for empty input and LONG_MAX or LONG_MIN for overflow or underflow. On empty input the return value is 0 and errno might be set to EINVAL; the portable way of checking for empty input is comparing p and str.

This will still accept strings that start with white space; check for !isspace((unsigned char)*str) if you want to reject them.

This entry was posted in Programming. Bookmark the permalink.

One Response to strtol() Usage Guide

  1. Haunted Ghost says:

    This was helpful in making a quick code with basic error handling..thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>