C strtol
strtol converts the leading digits of a string to a long. Its end pointer identifies the first unconsumed character, and errno reports range errors.
A simple example
strtol
- Start with "12"
- Do this Read a base-ten integer
- Result 12
Syntax
long strtol(const char *text, char **end, int base)
Run this example in C
Save the program as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
Reject a partial integer in a quantity field
A shipment or sensor form accepts a number as text. Check both the allowed range and how much input was consumed so a partial number, invalid field or overflowing value cannot pass as a normal reading.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void) {
const char *inputs[] = {"24", "24kg", ""};
for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; ++i) {
char *end;
errno = 0;
long value = strtol(inputs[i], &end, 10);
if (end == inputs[i] || *end != '\0' || errno == ERANGE || value < 0) {
puts("invalid");
} else {
printf("%ld\n", value);
}
}
return 0;
}
24 invalid invalid
The example accepts only a complete nonnegative base-ten quantity. Checking the end pointer distinguishes a genuine zero from an input with no digits. Reset errno before each call.
Open Group function reference for strtol
Read the afternoon delivery
A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?
Read an empty delivery count
A class receives a stock record whose quantity field is the character zero. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?