Robust string-to-number conversion with strtol
What you'll learn: How to reliably convert strings to integers while detecting errors that simpler functions like atoi ignore.
Why not atoi?
In earlier lessons, you might have used atoi ("ascii to integer"). It’s simple, but it has a dangerous flaw: if you give it a non-numeric string like "hello", it simply returns 0. You have no way of knowing if the user actually typed 0 or if the conversion failed entirely.
strtol (String to Long) is the professional alternative. Think of it as a quality-control inspector that doesn't just give you the number, but also tells you where it stopped reading and if it ran into trouble.
How it works
strtol takes three arguments: the string to convert, a pointer to a "remainder" string, and the numeric base (usually 10). The magic is in that second argument—the "end pointer." If the conversion is successful, this pointer will point to the character immediately following the number. If it points to the very start of your string, no numbers were found at all.
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *input = "42 stars";
char *endPtr;
// Convert string to long (base 10)
long value = strtol(input, &endPtr, 10);
if (input == endPtr) {
printf("No digits found.\n");
} else {
printf("Number found: %ld\n", value);
printf("Remaining text: %s\n", endPtr); // Outputs: " stars"
}
return 0;
}
Safety first
Because strtol stops as soon as it hits a non-numeric character, it is incredibly robust. You can use it to parse complex strings (like "100px") or to validate user input. If *endPtr is not a null terminator (\0) or a newline, you know there’s "garbage" left over in the string, allowing you to reject the input instead of proceeding with a broken value.
Key takeaway
Use strtol instead of atoi to distinguish between a valid zero and a failed conversion.