c++c++23

How to output hexadecimal formatted numbers with C++23 std::print?


I am using the new C++23 std::print function from the <print> utility.

I have found the information about how to format an integer value as a fixed width string with preceeding 0 characters (padding) however I cannot find the relevant documentation for how to print in hexadecimal format instead of decimal format, which is the default.

Here is an example

#include <print>
#include <format>

int value = 16;

std::print("{:02}", value);

Solution

  • There is a x specifier, which should be appended to the format string.

    std::print("{:02x}", value);
    

    Note that this requires gcc version 13, if you are using g++ on Linux, which supports C++ 23.