Go to the previous, next section.

Parsing of Integers

These functions are declared in `stdlib.h'.

Function: long int strtol (const char *string, char **tailptr, int base)

The strtol ("string-to-long") function converts the initial part of string to a signed integer, which is returned as a value of type long int.

This function attempts to decompose string as follows:

If the string is empty, contains only whitespace, or does not contain an initial substring that has the expected syntax for an integer in the specified base, no conversion is performed. In this case, strtol returns a value of zero and the value stored in *tailptr is the value of string.

In a locale other than the standard "C" locale, this function may recognize additional implementation-dependent syntax.

If the string has valid syntax for an integer but the value is not representable because of overflow, strtol returns either LONG_MAX or LONG_MIN (see section Range of an Integer Type), as appropriate for the sign of the value. It also sets errno to ERANGE to indicate there was overflow.

There is an example at the end of this section.

Function: unsigned long int strtoul (const char *string, char **tailptr, int base)

The strtoul ("string-to-unsigned-long") function is like strtol except that it returns its value with type unsigned long int. The value returned in case of overflow is ULONG_MAX (see section Range of an Integer Type).

Function: long int atol (const char *string)

This function is similar to the strtol function with a base argument of 10, except that it need not detect overflow errors. The atol function is provided mostly for compatibility with existing code; using strtol is more robust.

Function: int atoi (const char *string)

This function is like atol, except that it returns an int value rather than long int. The atoi function is also considered obsolete; use strtol instead.

Here is a function which parses a string as a sequence of integers and returns the sum of them:

sum_ints_from_string (char *string)
  int sum = 0;

  while (1) {
    char *tail;
    int next;

    /* Skip whitespace by hand, to detect the end.  */
    while (isspace (*string)) string++;
    if (*string == 0)

    /* There is more nonwhitespace,  */
    /* so it ought to be another number.  */
    errno = 0;
    /* Parse it.  */
    next = strtol (string, &tail, 0);
    /* Add it in, if not overflow.  */
    if (errno)
      printf ("Overflow\n");
      sum += next;
    /* Advance past it.  */
    string = tail;

  return sum;

Go to the previous, next section.