Описание тега strtol

NoneStrtol () is the C runtime library function for converting the text representation of a number to a long integer. This SO tag also applies to strtoll(), strtoul(), and strtoull() which perform the same conversion to types "long long", "unsigned long", and "unsigned long long".

Use this tag on for all questions about the use of the strtol() family of functions or where such a function does not seem to be working correctly.

Closely related are:

  • atoi for converting text to int (includes atol(), atoll(), and atoq())
  • atol() for long
  • atof for double
  • strtod for double with unambiguous error indication
  • scanf for converting one or more values at a time directed by a format specification

SYNPOSIS

#include <stdlib.h>

              long int strtol   (const char *nptr, char **endptr, int base);
         long long int strtoll  (const char *nptr, char **endptr, int base);
     unsigned long int strtoul  (const char *nptr, char **endptr, int base);
unsigned long long int strtoull (const char *nptr, char **endptr, int base);

BSD also has

                quad_t strtoq   (const char *nptr, char **endptr, int base);
              u_quad_t strtouq  (const char *nptr, char **endptr, int base);

strtol() converts from text in any base from 2 through 36. Or it can choose a base automatically (if base is specified as zero) same as the C compiler does depending on how the number is written: a leading 0 chooses octal, a leading 0x or 0X chooses hexadecimal, else decimal. Leading whitespace is skipped.

If endptr is not NULL, the pointer is set to the next character not converted. A conversion error is indicated by errno set to EINVAL (but set errno to zero before calling).

strtol() returns the result of the conversion, unless the value would underflow or overflow. It returns LONG_MIN if an underflow occurs, and LONG_MAX in case of an overflow. In both cases, errno is set to ERANGE. Similar is the case for strtoll() (LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX respectively).