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
- Start with "12"
- Do this Read a base-ten integer
- Result 12
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.
#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;
}
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
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?
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?