Table of Contents

With the introduction of C++17, the C++ Standard Library expanded its capabilities for converting text to numbers with the addition of std::from_chars. This low-level, high-performance API offers significant advantages over previous methods, such as atoi and stringstream. In this article, we will explore the evolution of string conversion routines from C++17 through C++26, highlighting key improvements like constexpr support and enhanced error handling. Let’s dive into the details and see how std::from_chars can transform your approach to string conversion.

Updated in Oct 2024: Added notes from constexpr support in C++23, and C++26 improvements, plus more Compiler Explorer examples.

Before C++17  

C++, before C++17, offered several options when it comes to string conversion:

  • sprintf / snprintf
  • sscanf
  • atol
  • strtol
  • strstream
  • stringstream
  • to_string
  • stoi and similar functions

And with C++17 you get another option: std::from_chars! Wasn’t the old stuff good enough? Why do we need new methods?

In short: because from_chars is low-level, and offers the best possible performance.

The new conversion routines are:

  • non-throwing
  • non-allocating
  • no locale support
  • memory safety
  • error reporting gives additional information about the conversion outcome

The API might not be the most friendly to use, but it’s easy enough to wrap it into some facade.

A simple example:

const std::string str { "12345678901234" };
int value = 0;
std::from_chars(str.data(),str.data() + str.size(), value);
// error checking ommited...

The Series  

This article is part of my series about C++17 Library Utilities. Here’s the list of the topics in the series:

Resources about C++17 STL:

Let’s have a look at the API now.

Converting From Characters to Numbers: from_chars  

std::from_chars, available in the <charconv> headers, is a set of overloaded functions: for integral types and floating point types.

For integral types we have the following functions:

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

Where TYPE expands to all available signed and unsigned integer types and char.

base can be a number ranging from 2 to 36.

Then there’s the floating point version:

std::from_chars_result from_chars(const char* first, 
                   const char* last, 
                   FLOAT_TYPE& value,
                   std::chars_format fmt = std::chars_format::general);

FLOAT_TYPE expands to float, double or long double.

chars_format is an enum with the following values: scientific,

fixed, hex and general (which is a composition of fixed and scientific).

The return value in all of those functions (for integers and floats) is from_chars_result:

struct from_chars_result {
    const char* ptr;
    std::errc ec;
};

from_chars_result holds valuable information about the conversion process.

Here’s the summary:

Return Condition State of from_chars_result
Success ptr points at the first character not matching the pattern, or has the value equal to last if all characters match and ec is value-initialized.
Invalid conversion ptr equals first and ec equals std::errc::invalid_argument. value is unmodified.
Out of range The number it too large to fit into the value type. ec equals std::errc::result_out_of_range and ptr points at the first character not matching the pattern. value is unmodified.

The new routines are very low level, so you might be wondering why is that. Titus Winters added a great summary in comments:

The intent of those APIs is *not* for people to use them directly, but to build more interesting/useful things on top of them. These are primitives, and we (the committee) believe they have to be in the standard because there isn’t an efficient way to do these operations without calling back out to nul-terminated C routines

Examples  

Here are two examples of how to convert a string into a number using from_chars, to int andfloat.

Integral types  

#include <charconv> // from_char, to_char
#include <string>
#include <iostream>

int main() {
    const std::string str { "12345678901234" };
    int value = 0;
    const auto res = std::from_chars(str.data(), 
                                     str.data() + str.size(), 
                                     value);

    if (res.ec == std::errc())
    {
        std::cout << "value: " << value 
                  << ", distance: " << res.ptr - str.data() << '\n';
    }
    else if (res.ec == std::errc::invalid_argument)
    {
        std::cout << "invalid argument!\n";
    }
    else if (res.ec == std::errc::result_out_of_range)
    {
        std::cout << "out of range! res.ptr distance: " 
                  << res.ptr - str.data() << '\n';
    }
}

The example is straightforward, it passes a string str into from_chars and then displays the result with additional information if possible.

your task is to run the code @Compiler Explorer.

Does “12345678901234” fit into the number? Or you see some errors from the conversion API?

Floating Point  

Here’s the floating pointer version:

#include <charconv> // from_char, to_char
#include <string>
#include <iostream>

int main() {
    const std::string str { "16.78" };
    double value = 0;
    const auto format = std::chars_format::general;
    const auto res = std::from_chars(str.data(), 
                                 str.data() + str.size(), 
                                 value, 
                                 format);

    if (res.ec == std::errc())
    {
        std::cout << "value: " << value 
                  << ", distance: " << res.ptr - str.data() << '\n';
    }
    else if (res.ec == std::errc::invalid_argument)
    {
        std::cout << "invalid argument!\n";
    }
    else if (res.ec == std::errc::result_out_of_range)
    {
        std::cout << "out of range! res.ptr distance: " 
                  << res.ptr - str.data() << '\n';
    }
}

Run at Compiler Explorer

Here’s the example output that we can get:

str value format value output
1.01 fixed value: 1.01, distance 4
-67.90000 fixed value: -67.9, distance: 9
20.9 scientific invalid argument!, res.ptr distance: 0
20.9e+0 scientific value: 20.9, distance: 7
-20.9e+1 scientific value: -209, distance: 8
F.F hex value: 15.9375, distance: 3
-10.1 hex value: -16.0625, distance: 5

The general format is a combination of fixed and scientific so it handles regular floating point string with the additional support for e+num syntax.

Performance  

I did some benchmarks, and the new routines are blazing fast!

Some numbers:

  • On GCC it’s around 4.5x faster than stoi, 2.2x faster than atoi and almost 50x faster than istringstream.
  • On Clang it’s around 3.5x faster than stoi, 2.7x faster than atoi and 60x faster than istringstream!
  • MSVC performs around 3x faster than stoi, ~2x faster than atoi and almost 50x faster than istringstream

You can find the results in my book on C++17: C++17 In Detail.

C++23 Updates  

In C++23 we got one improvement for our functions: P2291

constexpr for integral overloads of std::to_chars() and std::from_chars().

It’s already implemented in GCC 13, Clang 16, and MSVC 19.34.

Together with std::optional that can also work in the constexpr context we can create the following example:

#include <charconv>
#include <optional>
#include <string_view>

constexpr std::optional<int> to_int(std::string_view sv)
{
    int value {};
    const auto ret = std::from_chars(sv.begin(), sv.end(), value);
    if (ret.ec == std::errc{})
        return value;

    return {};
};

int main() {
    static_assert(to_int("hello") == std::nullopt);
    static_assert(to_int("10") == 10);
}

Run @Compiler Explorer

C++26 Updates  

The work is not complete, and looks like in C++26 we’ll have more additions:

See P2497R0 wchich is already accepted into the working draft of C++26:

Testing for success or failure of <charconv> functions

The feature is already implemented in GCC 14 and Clang 18.

In short from_chars_result (as well as to_chars_result) gets a bool conversion operator:

constexpr explicit operator bool() const noexcept;

And it has to return ec == std::errc{}.

This means our code can be a bit simpler:

if (res.ec == std::errc()) { ... }

can become:

if (res) { ... }

For example:

// ...
const auto res = std::from_chars(str.data(), 
                                 str.data() + str.size(), 
                                 value, 
                                 format);

if (res)
{
    std::cout << "value: " << value 
              << ", distance: " << res.ptr - str.data() << '\n';
}
// ...

Run @Compiler Explorer

Compiler Support for std::from_chars in C++  

  • Visual Studio: Full support for std::from_chars was introduced in Visual Studio 2019 version 16.4, with floating-point support starting from VS 2017 version 15.7. Visual Studio 2022 includes C++23 features like constexpr for integral overloads.

  • GCC: Starting with GCC 11.0, std::from_chars offers full support, including integer and floating-point conversions. The latest GCC versions, such as GCC 13, incorporate constexpr integral support.

  • Clang: Clang 7.0 introduced initial support for integer conversions. Clang 16 and above support constexpr for integral overloads.

For the most accurate and up-to-date information see CppReference, Compiler Support.

Summary  

If you want to convert text into a number and you don’t need any extra stuff like locale support then std::from_chars might be the best choice. It offers great performance, and what’s more, you’ll get a lot of information about the conversion process (for example how much characters were scanned).

The routines might be especially handy with parsing JSON files, 3d textual model representation (like OBJ file formats), etc.

What’s more the new functions can be evan used at compile-time (as of C++23), and have even better error checking in C++26.

References  

If you want to read more about existing conversion routines, new ones and also see some benchmarks you can see two great posts at @fluentcpp:

Your Turn

  • Have you played with the new conversion routines?
  • What do you usually use to convert text into numbers?