c / intermediate
Snippet
Robust Numeric Parsing with strtol
Unlike the simpler atoi(), strtol() provides robust error checking and handles different number bases. It detects overflow, empty inputs, and tells you exactly where the numeric portion ends by updating the 'endptr' pointer, making it the industry standard for string-to-number conversion.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>#include <stdlib.h>#include <errno.h>int main() {const char *input = " 1024abc";char *endptr;errno = 0;long val = strtol(input, &endptr, 10);if (input == endptr) {printf("No digits were found\n");} else if (errno != 0) {perror("Conversion error");} else {printf("Value: %ld, Remainder: '%s'\n", val, endptr);}return 0;}
Breakdown
1
long val = strtol(input, &endptr, 10);
Converts string to long using base 10; endptr points to the first non-numeric character.
2
if (input == endptr)
Checking if the pointer moved; if not, no conversion happened.
3
errno = 0;
Resetting the global error number before calling the function to catch overflow/underflow.