Lesson contents

C — Validating integers with strtol

In C, strtol parses a number and exposes where it stopped. Validate the entire token and check the permitted range before storing the result through an output pointer.

A simple example

Turn text into a number

  1. Start with "2"
  2. Do this Read an integer, add 1
  3. Result 3
The conversion produces the number 2. Adding one now gives 3.
lesson.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char *end;
    long n = strtol("2", &end, 10);
    if (*end == '\0') printf("%ld\n", n + 1);
}
Output
3
Advertisements

Validate a seat number

strspn checks that the entire token consists of decimal digits before strtol converts it. The function checks ERANGE and writes to the output pointer only on success. The caller supplies the address of a live int.

Seat 3: Accept. Seat 0: Out of range. Seat x: Invalid number.
Validate a seat request

A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.

Run the example

C17. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 lesson.c -o lesson
./lesson
lesson.c
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

int seat_number(const char *text, int *seat) {
    if (*text == '\0' || text[strspn(text, "0123456789")] != '\0') return 0;
    errno = 0;
    long n = strtol(text, NULL, 10);
    if (errno == ERANGE || n < 1 || n > 8) return 0;
    *seat = (int)n;
    return 1;
}

int main(void) {
    const char *inputs[] = {"3", "0", "x"};
    for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; ++i) {
        int seat;
        if (seat_number(inputs[i], &seat)) printf("%d\n", seat);
        else puts("invalid");
    }
    return 0;
}
Output
3
invalid
invalid

Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.

Try it yourself

Predict the results for 8, 9, and an empty string.

Check your answer

Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.

GNU C Language Manual

Related tags

  • C
  • validation
  • errors
  • optional values