Go to the previous, next section.
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:
isspace function
(see section Classification of Characters). These are discarded.
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'.
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 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:
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;
}
Go to the previous, next section.