Examples

Below we take a look at the floating and integral type string conversions!

We'll cover the following...

Here are two examples of how to convert a string into a number using from_chars. The first one will convert into int and the second one converts into a floating-point number.

Integral types

Press + to interact
#include <iostream>
#include <charconv> // from_chars, to_chars
#include <string>
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.

Below you can find an output for various str value.

str value Output
...