strtol() Convert a string to long and report the endpoint
strtol() Convert a string to long and report the endpoint
strtol() converts a prefix to long in base 0 or 2-36 and reports the stop position. Clear errno, then check endptr and ERANGE for input and range errors.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
long int strtol(const char *nptr, char **endptr, int base);
⚙️ Parameters
| nptr Required | The null-terminated string to parse. |
|---|---|
| endptr Optional | If not NULL, receives a pointer to the first character that was not parsed. |
| base Required | The conversion base, either 0 or between 2 and 36; zero infers the base from prefixes. |
Returns: Returns the converted value on success, or 0 if no conversion is possible. On range error, returns LONG_MAX or LONG_MIN and sets errno to ERANGE.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Value: 123
Remainder: abc
⚠️ Warning Set errno to zero before the call, then check range errors and end == nptr separately. The return value alone cannot reliably validate the input.
💡 Tip With base 0, a leading 0 selects octal and 0x selects hexadecimal. Pass 10 when input must always be decimal.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QHow should I use the endptr argument of strtol?
APass the address of a char *end. After the call, end == nptr means no digits were parsed, *end == '\0' means the entire string was consumed, and otherwise end points to the suffix.
QWhat happens when strtol is called with base 0?
AThe function infers the base like a C integer constant: 0x or 0X selects hexadecimal, a leading 0 selects octal, and otherwise decimal is used.
QWhy should errno be set to 0 before calling strtol?
AA successful strtol call need not clear an existing errno value, so if errno is already ERANGE, you cannot tell whether the current conversion caused a range error. Set errno to 0 first, then check whether it becomes ERANGE; also use endptr to determine whether a conversion occurred and whether the entire input was consumed.