Codectionary / Developer documentation / C++

C++ std::from_chars parsing

C++17 from_chars parses numbers without throwing or using the locale. The returned pointer identifies the first unconsumed character, so success and full-input consumption are separate checks.

Syntax

auto result = std::from_chars(first, last, value);

Examples

C++ std::from_chars parsing

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <charconv>
#include <string_view>
#include <system_error>
#include <iostream>
int main() {
    std::string_view input = "240";
    int port = 0;
    auto result = std::from_chars(input.data(), input.data() + input.size(), port);
    if (result.ec == std::errc{} && result.ptr == input.data() + input.size())
        std::cout << port + 1 << '\n';
    else std::cout << "Invalid number\n";
}
  1. Output: 241. Changing input to 240x takes the invalid branch even though the numeric prefix is valid.

Best practices

  • Check both ec and ptr. Integer parsing does not skip leading whitespace or accept a leading plus sign.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading