c++17 to_chars,from_chars, if, structured binding

explain

std::to_chars

By successfully filling in the range [first, last], convert value to a string. It is required that [first, last) is a legal range.

  1. Integer formatting function: value is a string converted to digits with a given base base (leading zeros without redundancy). The numbers in the range 10... 35 (including upper and lower bounds) are represented as lowercase letters a... z. if the value is less than zero, it starts with a negative sign. The library provides all signed and unsigned integers and char types as overloads of parameter value type.
  2. The overload of bool has been removed. to_chars rejects bool type parameters because if allowed, the result will be "0" / "1" instead of "false" / "true".
  3. As std::sprintf is used in the default ("C") local environment to convert the value into a string. The conversion specifier is f or e, which is selected according to the requirements of the shortest representation (F is preferred if the two are equivalent): the string is represented by the decimal point (if any) There is at least one character in the front, and the corresponding std::from_chars is used to analyze the composition of the minimum number of characters that can accurately restore the value. If there are several such representations, the one with the smallest difference to value is selected, and any residual tendency is solved by rounding according to std::round_to_nearest
  4. The same as (3), but if fmt is std::chars_format::fixed, the conversion of the corresponding printf is specified as f; if fmt is std::chars_format::scientific, it is e; if fmt is std::chars_format::hex, it is a (but the result has no leading "0x"), and if fmt is chars_format::general, it is g.
  5. The same as (4), except that the precision is specified by the parameter precision, rather than the shortest.
  6. Return type (see return value later). std::to_chars_result has no base class or members other than ptr, ec and implicitly declared special member functions.
    parameter
    first, last - the range of characters to write
    Value - the value to convert to its string representation
    Base - integer base used: value between 2 and 36 (including upper and lower limits).
    fmt - floating point format used, bit mask of type std::chars_format
    Precision - floating point precision used
    Return value
    When successful, a value of type to_chars_result is returned. Its ec is equal to std::errc initialized by the value, and its ptr is a pointer to the last position of the written character. Note that the string is not null terminated.
    In case of error, return a value of type to_chars_result, which holds std::errc::value_too_large in ec, last in ptr, and leaves content in unspecified state in the range [first, last].

std::from_chars

Analyze the character sequence [first,last) according to the following pattern. If there is no character matching pattern or if the value obtained according to the analysis matching character cannot be expressed in the type of value, the value will not be modified. Otherwise, the character of the matching pattern will be translated into the text representation of the arithmetic value and the value will be stored in value.

  1. Integer analysis function: expect the same pattern as std::strtol used in the default ("C") local environment, and give a non-zero integer base, except
    Prefix '0x' or '0x' is not recognized for base 16
    Only negative signs are recognized (no positive signs are recognized), and only for the signed integer type of value.
    The library provides overloads for all signed and unsigned integer types and char, which are the referenced types of the parameter value.
    2-4) floating point analysis function: expect that std::strtod is the same as the default ("C") local environment, except
    Positive signs outside the index are not recognized (only negative signs are allowed at the starting position)
    If fmt sets std::chars_format::scientific without std::chars_format::fixed, the index part is required (otherwise optional)
    If fmt sets std::chars_format::fixed without std::chars_format::scientific, optional exponential part is not allowed
    Prefix "0x" or "0x" is not allowed if fmt is std::chars_format::hex (string "0x123" parsed as value "0" and the remaining "x123" not parsed).
    In any case, after rounding according to std::round_to_nearest, the result value is one of the floating-point values of at most two string values closest to the matching pattern.
  2. Return value type (see return value later). std::from_chars_result has no base class or members other than ptr, ec and implicitly declared special member functions.
    parameter
    first, last - the range of legal characters to analyze
    Value - stores the output parameter of the analyzed value. If the analysis is successful
    Base - integer base used: value between 2 and 36 (including upper and lower limits).
    fmt - floating point format used, bit mask of type std::chars_format
    Return value
    When successful, a value of type from_chars_result is returned. Its ptr points to the first character that does not match the pattern, or if all characters match, it points to a value equal to last, and its ec is initialized by the value.
    If there is no matching pattern, return a value of type from_chars_result, whose ptr is equal to first and ec is equal to std::errc::invalid_argument. Do not modify the value.
    If the pattern matches, but the analyzed value is not within the range represented by the type of value, return a value of type from_chars_result, whose ec is equal to std::errc::result_out_of_range, and ptr points to the character of the first mismatched pattern. Do not modify the value.

Sample code

#include <iostream>
#include <charconv>
#include <system_error>
#include <string_view>
#include <array>


struct StructBind {
    int a;
    std::string b;
};

StructBind Test(const int a,  const std::string& b)
{
    StructBind ss;
    ss.a = a;
    ss.b = b;
    return ss;
}

/*
std::to_chars
 By successfully filling in the range [first, last], convert value to a string. It is required that [first, last) is a legal range.
1) Integer formatting function: value is a string converted from a given base base to digits (leading zeros without redundancy). The numbers in the range 10.. 35 (including upper and lower bounds) are represented as lowercase letters a..z. if the value is less than zero, it starts with a negative sign. The library provides all signed and unsigned integers and char types as overloads of parameter value type.
2) bool The overload of was removed. to_chars rejected the bool type parameter because if allowed, the result would be "0" / "1" instead of "false"/"true".
3) As std::sprintf is used in the default ("C") local environment to convert the value into a string. The conversion specifier is f or e, which is selected according to the requirements of the shortest representation (F is preferred if the two are equivalent): the string is represented by the decimal point (if any) There is at least one character in the front, and the corresponding std::from_chars is used to analyze the composition of the minimum number of characters that can accurately restore the value. If there are several such representations, the one with the smallest difference to value is selected, and any residual tendency is solved by rounding according to std::round_to_nearest
4) The same as (3), but if fmt is std::chars_format::fixed, the conversion of the corresponding printf is specified as f; if fmt is std::chars_format::scientific, it is e; if fmt is std::chars_format::hex, it is a (but the result has no leading "0x"), and if fmt is chars_format::general, it is g.
5) The same as (4), except that the precision is specified by the parameter precision, rather than the shortest.
6) Return type (see return value later). std::to_chars_result has no members other than the base class or ptr, ec and implicitly declared special member functions.
parameter
first, last	-	Character range to write
value	-	The value to convert to its string representation
base	-	Integer base used: the value between 2 and 36 (including upper and lower limits).
fmt	-	Floating point format used, STD:: chars_ Bitmask of type format
precision	-	Floating point precision used
 Return value
 When successful, return to_ chars_ The value of result type, whose ec is equal to std::errc initialized by the value, and whose ptr is a pointer to the last position of the written character. Note that the string is not null terminated.
In case of error, return to_ chars_ The value of result type, which contains STD:: ERRC:: value in ec_ too_ Large, hold last in ptr, and leave content in unspecified state in the range [first, last].

std::from_chars
 Analyze the character sequence [first,last) according to the following pattern. If there is no character matching pattern or if the value obtained according to the analysis matching character cannot be expressed in the type of value, the value will not be modified. Otherwise, the character of the matching pattern will be translated into the text representation of the arithmetic value and the value will be stored in value.
1) Integer analysis function: expect the same pattern as std::strtol used in the default ("C") local environment, and give a non-zero integer base, except
 Prefix '0x' or '0x' is not recognized for base 16
 Only negative signs are recognized (no positive signs are recognized), and only for the signed integer type of value.
The library provides overloads for all signed and unsigned integer types and char, which are the referenced types of the parameter value.
2-4) Floating point analysis function: expect the same pattern as std::strtod used in the default ("C") local environment, except
 Positive signs outside the index are not recognized (only negative signs are allowed at the starting position)
If fmt sets std::chars_format::scientific without std::chars_format::fixed, the index part is required (otherwise optional)
If fmt sets std::chars_format::fixed without std::chars_format::scientific, optional exponential part is not allowed
 Prefix "0x" or "0x" is not allowed if fmt is std::chars_format::hex (string "0x123" parsed as value "0" and the remaining "x123" not parsed).
In any case, after rounding according to std::round_to_nearest, the result value is one of the floating-point values of at most two string values closest to the matching pattern.
5) Return value type (see return value later). std::from_chars_result has no base class or members other than ptr, ec and implicitly declared special member functions.
parameter
first, last	-	Legal character range to analyze
value	-	Store the output parameters of the analyzed value. If the analysis is successful
base	-	Integer base used: the value between 2 and 36 (including upper and lower limits).
fmt	-	Floating point format used, bit mask of type std::chars_format
 Return value
 When successful, a value of type from_chars_result is returned. Its ptr points to the first character that does not match the pattern, or if all characters match, it points to a value equal to last, and its ec is initialized by the value.
If there is no matching pattern, return a value of type from_chars_result, whose ptr is equal to first and ec is equal to std::errc::invalid_argument. Do not modify the value.
If the pattern matches, but the analyzed value is not within the range represented by the type of value, return a value of type from_chars_result, whose ec is equal to std::errc::result_out_of_range, and ptr points to the character of the first mismatched pattern. Do not modify the value.
*/


int main()
{
    std::array<char, 10> str;
    // c++ 17 if ( ; )
    int a{ 1 }, b{ 0 };
    if (a = b; 0 == a)
        std::cout << "a:"<<a <<", b:" << b << "\n";
    // c++17 
    auto [c, d] = Test(1, "2");
    std::cout << "c:" << c << ", d:"<<d << "\n";
    // Advanced Edition    
    // to_chars
    if (auto [p, ec] = std::to_chars(str.data(), str.data() + str.size(), 255, 16); ec == std::errc())
    {
        std::cout << "str:\t" << std::string_view(str.data(), p - str.data()) << "\n";
    }
    std::array<char, 10> str2{"123.456"};
    double value{ 0 };
    // from_chars
    if (auto [p, ec] = std::from_chars(str2.data(), str2.data() + str2.size(), value, std::chars_format::general); ec == std::errc())
    {
        std::cout << "value:\t" << value << "\n";
    }
    return 0;
}

output

a:0, b:0
c:1, d:2
str:    ff
value:  123.456

reference resources

https://zh.cppreference.com/w/cpp/utility/from_chars
https://zh.cppreference.com/w/cpp/utility/to_chars

Tags: C++

Posted on Tue, 23 Nov 2021 23:35:09 -0500 by biscutty