strtol() — Convert character string to long
Standards
| Standards / Extensions | C or C++ | Dependencies |
|---|---|---|
ISO C
XPG4 XPG4.2 C99 Single UNIX Specification, Version 3 |
both |
Format
#include <stdlib.h>
long int strtol(const char * __restrict__nptr, char ** __restrict__endptr, int base);General description
Converts nptr, a character string, to a long int value.
- A sequence of characters, which in the current locale are defined as white space characters. This part may be empty.
- A sequence of characters interpreted as integer in some base notation. This is the subject sequence.
- A sequence of unrecognized characters.
- 10
- Sequence starts with nonzero decimal digit.
- 8
- Sequence starts with 0, followed by a sequence of digits with values from 0 to 7.
- 16
- Sequence starts with either
0xor0X, followed by digits, and lettersAthroughForathroughf.
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.
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.
Returned value
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:
- Error Code
- Description
- EINVAL
- The value of base is not supported.
- ERANGE
- The conversion caused an overflow.
Example
/* 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 932Related information
- stdlib.h — Standard library functions
- atof() — Convert character string to double
- atoi() — Convert character string to integer
- atol() — Convert character string to long
- fscanf(), scanf(), sscanf() — Read and format data
- strtod() — Convert character string to double
- strtoul() — Convert string to unsigned integer
