These functions are declared in `stdlib.h'.
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:
A (possibly empty) sequence of whitespace characters. Which characters are whitespace is determined by the isspace
function (see Classification of Characters). These are discarded.
An optional plus or minus sign (`+' or `-').
A nonempty sequence of digits in the radix specified by base.
If base is zero, decimal radix is assumed unless the series of digits begins with `0' (specifying octal radix), or `0x' or `0X' (specifying hexadecimal radix); in other words, the same syntax used for integer constants in C.
Otherwise base must have a value between 2
and 35
. If base is 16
, the digits may optionally be preceded by `0x' or `0X'.
Any remaining characters in the string. If tailptr is not a null pointer, strtol
stores a pointer to this tail in *tailptr
.
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 Range of 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.
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 Range of Type).
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.
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:
int 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) break; /* 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"); else sum += next; /* Advance past it. */ string = tail; } return sum; }