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.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

long int strtol(const char *nptr, char **endptr, int base);

⚙️ Parameters

nptr RequiredThe null-terminated string to parse.
endptr OptionalIf not NULL, receives a pointer to the first character that was not parsed.
base RequiredThe 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏