page-fault

Chapter 11: String Conversion

C++17 adds functions for fast low-level string conversion.

Current Issues

Solution

std::from_chars

std::from_chars_result from_chars (const char* first,
                                   const char* last,
                                   TYPE& value,
                                   int base = 10);
struct from_chars_result
{
    const char* ptr;
    std::errc ec;
};

Conversion Information

std::from_chars_result from_chars (const char* first,
                                   const char* last,
                                   TYPE& value,
                                   int base = 10);

struct from_chars_result {
    const char* ptr;
    std::errc ec;
};
std::string_view numbers {"1234"};
int value = 0;
const auto r = std::from_chars (numbers.data(),
                                numbers.data() + numbers.size(),
                                value);
if      (r.ec == std::errc())                    { std::cout << value << "\n"; }
else if (r.ec == std::errc::invalid_argument)    { std::cout << "invalid\n"; }
else if (r.ec == std::errc::result_out_of_range) { std::cout << "out of range\n"; }
input: 1234             value: 1234
input: 12345678901234   value: out of range
input: asdfa            value: invalid

std::to_chars

Conversion Information

std::to_chars_result to_chars (const char* first,
                               const char* last,
                               TYPE& value,
                               int base = 10);

struct to_chars_result {
    const char* ptr;
    std::errc ec;
};
std::string text {"xxxxxx"};
const int value = 1234;
const auto r = std::to_chars (text.data(),
                              text.data() + text.size(),
                              value);

if (r.ec == std::errc())
    std::cout << text << "\n";
else
    std::cout << "too large\n";
input: 1234         value: 1234xx
input: 12345678     value: too large

Benchmark: From Characters

from_char

Benchmark: To Characters

to_char

Guidelines