Library contents

C++ std::from_chars and std::errc

Check whether the entire quantity field can be read as a whole number before accepting it.

A simple example

std::from_chars and std::errc

  1. Start with Text "x"
  2. Do this Parse as a whole decimal number
  3. Result Invalid integer
There is no digit to convert. Handle the failed conversion before using the value.

Syntax

C++ syntax
std::from_chars(first, last, value)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

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

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

From the programstd::string field = "12x"
ResultCheck quantity
lesson.cpp
#include <charconv>
#include <iostream>
#include <string>

int main() {
    std::string field = "12x";
    int value = 0;
    auto result = std::from_chars(field.data(), field.data() + field.size(), value);
    if (result.ec != std::errc{} || result.ptr != field.data() + field.size() || value < 0)
        std::cout << "Check quantity\n";
    else
        std::cout << value << "\n";
    return 0;
}
Output
Check quantity

The customer typed 12x. The trailing letter makes the whole field invalid, so the program asks for a correction.

Advertisements

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.

Given24
Worked resultQuantity accepted

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.

Given4kg
Worked resultReview quantity

What to watch for

A successful conversion only establishes that the text is an integer. Validate the allowed order range separately.

Documentation for std::from_chars and std::errc