C++ charconv Header



In C++ the <charconv> header file provides two primary functions which offers efficient, low level ways to convert character sequences such as(std::string or char arrays) to numeric values. Designed to be faster and use less memory than alternatives and supports various formats and ranges.

Including Header

To use the charconv module in C++, we need to include the cfenv header file as shown below.

#include <charconv>

Functions

The two primary functions provided by <charconv> header are as follows.

S.NO Function & Description
1 from_chars()

This function converts a character sequence to an integer or floating-point value.

2 to_chars()

This function converts an integer or floating-point value to a character sequence.

Converting Character Sequence to Integer

In the below example code we are going to use, from_chars to convert character sequence to integer value or floating-point.

#include <iostream>
#include <charconv>
#include <string>
int main() {
   std::string str = "12345";
   int value;
   auto result = std::from_chars(str.data(), str.data() + str.size(), value);
   if (result.ec == std::errc()) {
      std::cout << "Converted integer: " << value << std::endl;
   } else {
      std::cout << "Conversion failed!" << std::endl;
   }
   return 0;
}

Output

If we run the above code it will generate the following output

Converted integer: 12345
Advertisements