Library contents

C++ std::from_chars

std::from_chars parses a range of characters and returns an error code and a pointer to the first unconsumed character.

A simple example

std::from_chars

  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
std::from_chars(first, last, value)
Run this example in C++

Save the program as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Parse a whole quantity field without exceptions

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 programint value = 0
First output line42
lesson.cpp
#include <iostream>
#include <charconv>
#include <string_view>
#include <system_error>

int main() {
    for (std::string_view field : {"42", "42kg", " 42"}) {
        int value = 0;
        const char *end = field.data() + field.size();
        auto result = std::from_chars(field.data(), end, value);
        if (result.ec == std::errc{} && result.ptr == end)
            std::cout << value << '\n';
        else
            std::cout << "invalid\n";
    }
    return 0;
}
Output
42
invalid
invalid

A successful prefix conversion can leave a suffix. Check the pointer against last to reject units. Integer parsing also rejects leading whitespace, a useful property for strict record formats.

C++ working draft for std::from_chars

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