Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdlib.h>
long int strtol(const char * __restrict__nptr, char ** __restrict__endptr, int base);
Converts nptr, a character string, to a long int value.
If the base is greater than zero, the subject sequence contains decimal digits and letters, possibly preceded by either a plus or a minus sign. The letters a (or A) through z (or Z) represent values from 10 through 36, but only those letters whose value is less than the value of the base are allowed.
>>-+-------------+--+-----+--+----+--+--------+---------------->< '-white space-' +- + -+ +-0--+ '-digits-' '- - -' +-0x-+ '-0X-'
The pointer to the converted characters, even if conversion was unsuccessful, is stored in the object pointed to by endptr, as long as endptr is not a NULL pointer.
If successful, strtol() returns the converted long int value.
If unsuccessful, strtol() returns 0 if no conversion could be performed. If the correct value is outside the range of representable values, strtol() returns LONG_MAX or LONG_MIN, according to the sign of the value. If the value of base is not supported, strtol() returns 0.
If unsuccessful strtol() sets errno to one of the following values:
⁄* CELEBS55
This example converts the strings to a long.
It prints out the converted value and the substring that
stopped the conversion.
*⁄
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *string, *stopstring;
long l;
int bs;
string = "10110134932";
printf("string = %s\n", string);
for (bs = 2; bs <= 8; bs *= 2)
{
l = strtol(string, &stopstring, bs);
printf(" strtol = %ld (base %d)\n", l, bs);
printf(" Stopped scan at %s\n\n", stopstring);
}
}
string = 10110134932
strtol = 45 (base 2)
Stopped scan at 34932
strtol = 4423 (base 4)
Stopped scan at 4932
strtol = 2134108 (base 8)
Stopped scan at 932