Open In App

C++17 – <charconv> Header

Last Updated : 29 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The C++ <charconv> header provides many functions for converting the character sequences to numerical values and vice-versa. It is considered better than the <cstdlib> header file functions for the same purpose. The functions provided by the <charconv> header file are generally faster than the functions provided by the <cstdlib> header file. 

 It was introduced in C++17 and the main point of designing this header was to improve the complexity and performance of the code.

Functions in <charconv> Header

There are two functions available in charconv library which are:

1. to_chars()

The to_chars() function is used to convert a number to its corresponding character representation and stores the result in a buffer.

Syntax

to_chars_result to_chars( char* first, char* last, T value );

Parameters

  • First and last: Pointers to the beginning and end of the buffer where the output will be written.
  • value: The numeric value to be converted.

Return Value

  • It returns the object of type to_chars_result which contains two members:
    • ptr: A pointer to the first character after the end pointer of the characters written.
    • ec: It is an error code that determines if the conversion is successful or not. If the conversion is successful, the error code will be set to errc else it will be set to an error code if an error occurred.

Example

This code demonstrates how to use the to_chars() function from the <charconv> header to convert an integer value to a character sequence.

C++




// C++ program to illustrate the use of to_chars() function
#include <array>
#include <charconv>
#include <iostream>
using namespace std;
  
int main()
{
    // Buffer to store the resulting characters
    array<char, 10> buffer;
    // The integer value to convert
    int val = 42;
  
    // Convert the integer value to a character sequence
    auto result = to_chars(
        buffer.data(), buffer.data() + buffer.size(), val);
  
    // Check if the conversion was successful
    if (result.ec == errc()) {
        // If successful, print the converted value
        cout << "Converted value: "
             << string_view(buffer.data(),
                            result.ptr - buffer.data())
             << endl;
    }
  
    return 0;
}


Output

Converted value: 42

2. from_chars()

The from_chars() function is used to convert the character representation of a number to its corresponding numeric representation.

Syntax

from_chars_result from_chars( const char* first, const char* last, T& value );

Parameters

  • first and last: Pointers to the beginning and end of the character to be converted.
  • value: Reference to the numeric value to be converted.

Return Value

  • It returns the object of type from_chars_result which contains two members:
    • ptr: A pointer to the first character after the end pointer of the characters written.
    • ec: It is an error code that determines if the conversion is successful or not. If the conversion is successful, the error code will be set to errc else it will be set to an error code if an error occurred.

Example 1:

This code demonstrates how to use the from_chars() function from the <charconv> header to convert a string to an integer value.

C++




// C++ program to demonstrate the use of from_chars()
// function
#include <charconv>
#include <iostream>
using namespace std;
  
int main()
{
    // Declare a string variable and assign it the value
    // "42"
    string str = "42";
  
    // Declare an integer variable to hold the converted
    // value
    int val;
  
    // Call the from_chars function to convert the string to
    // an integer
    auto result = from_chars(str.data(),
                             str.data() + str.size(), val);
  
    // Check if the conversion was successful
    if (result.ec == errc()) {
        // If successful, print the converted value
        cout << val << endl;
    }
  
    return 0;
}


Output

42

Example 2:

This code demonstrates how to use the from_chars() function from the <charconv> header to convert a string to a double value.

C++




// c++ program to illustrate the conversion of string to
// double using from_chars()
#include <charconv>
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    // Input string to be converted
    string str = "1234.56";
    // Variable to store the converted value
    double value = 0.0;
  
    // Using std::from_chars to convert the string to a
    // double value
    // The result of the conversion is stored in 'value'
    // 'ptr' is a pointer to the character in the string
    // that follows the converted value 'ec' is an error
    // code that indicates whether the conversion was
    // successful
    auto [ptr, ec] = from_chars(
        str.data(), str.data() + str.size(), value);
  
    // If the conversion was successful (no error)
    if (ec == errc{}) {
  
        // Print the converted value
        cout << "Converted value: " << value << endl;
    }
    // If the conversion failed
    else {
  
        // Print the error code indicating the reason for
        // the failure
        cout << "Conversion failed with error code "
             << static_cast<int>(ec) << endl;
    }
  
    return 0;
}


Output

Converted value: 1234.56

Advantages of Using <charconv>

Following are the few advantages of using <charconv> library functions in C++:

  • Performance: This header has a lot of standard functions that minimize memory allocation and improve the performance of the code.
  • Error handling: It produces the from_chars_result that will tell you whether the conversation was a success or it has some error.
  • Flexibility: It can handle a wide range of input formats and ensures the scalability of the code.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads