Library contents

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

  1. Start with "12"
  2. Do this Read a base-ten integer
  3. Result 12
The characters 1 and 2 represent one ten and two ones. The resulting number can be used in arithmetic.

Syntax

C 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.

From the programconst char *inputs[] = {"24", "24kg", ""}
First output line24
lesson.c
#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;
}
Output
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

Advertisements

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?

Given“18” + 2 on hand
Worked result20

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?

Given“0” + 2 on hand
Worked result2