C strtol and errno
Check whether the entire quantity field can be read as a whole number before accepting it.
A simple example
strtol and errno
- Start with Text "x"
- Do this Parse as a whole decimal number
- Result Invalid integer
Syntax
strtol(field, &end, 10)
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonReject a mistyped order quantity
A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
int main(void) {
char *end;
const char *field = "12x";
errno = 0;
long value = strtol(field, &end, 10);
if (end == field || *end != '\0' || errno == ERANGE || value < 0) {
puts("Check quantity");
} else {
printf("%ld\n", value);
}
return 0;
}
Check quantity
The customer typed 12x. The trailing letter makes the whole field invalid, so the program asks for a correction.
Read a donation total
The library has a signed-off box count written as decimal digits. Parse the entire quantity as a base-ten integer. Let the clerk correct a rejected record.
Catch a unit in the count field
An equipment form expects an integer but the donor types the unit as well. Parse the entire quantity as a base-ten integer. Let the clerk correct a rejected record.
What to watch for
A successful conversion only establishes that the text is an integer. Validate the allowed order range separately.