Table of Contents

<charconv>

<charconv> provides fast, locale-independent number-to-string and string-to-number conversion via std::to_chars and std::from_chars. Unlike std::stoi or string streams, these don't throw exceptions—they return an error code and the number of characters consumed.

It's used in performance-critical paths like serialization, parsing CSV, or network protocols where you want predictable performance without locale assumptions.

Example

This example converts an integer to a character buffer and parses a string back to an integer, using error codes instead of exceptions.

// compile: g++ -std=c++17 -o charconvexample charconvexample.cpp
// run: ./charconvexample
// description: fast integer and float conversion
 
#include <charconv>
#include <iostream>
#include <string>
 
int main() {
    char buffer[32];
 
    auto [ptr, ec] = std::to_chars(buffer, buffer + 32, 12345);
    std::cout << "to_chars(12345): " << std::string(buffer, ptr) << "\n";
 
    const char* str = "67890";
    int value;
    auto result = std::from_chars(str, str + 5, value);
    if (result.ec == std::errc()) {
        std::cout << "from_chars('67890'): " << value << "\n";
    }
 
    return 0;
}