std::printf, std::fprintf, std::sprintf, std::snprintf
Min standard notice:
Header: <cstdio>
Loads the data from the given locations, converts them to character string equivalents and writes the results to a variety of sinks.
# Declarations
int printf( const char* format, ... );
int fprintf( std::FILE* stream, const char* format, ... );
int sprintf( char* buffer, const char* format, ... );
int snprintf( char* buffer, std::size_t buf_size, const char* format, ... );
(since C++11)
# Parameters
stream: output file stream to write tobuffer: pointer to a character string to write tobuf_size: up to buf_size - 1 characters may be written, plus the null terminatorformat: pointer to a null-terminated multibyte string specifying how to interpret the data...: arguments specifying data to print. If any argument after default argument promotions is not the type expected by the corresponding conversion specification (the expected type is the promoted type or a compatible type of the promoted type), or if there are fewer arguments than required by format, the behavior is undefined. If there are more arguments than required by format, the extraneous arguments are evaluated and ignored
# Notes
POSIX specifies that errno is set on error. It also specifies additional conversion specifications, most notably support for argument reordering (n$ immediately after % indicates nth argument).
Calling std::snprintf with zero buf_size and null pointer for buffer is useful (when the overhead of double-call is acceptable) to determine the necessary buffer size to contain the output:
# Example
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <limits>
int main()
{
const char* s = "Hello";
std::printf("Strings:\n"); // same as std::puts("Strings:");
std::printf("\t[%10s]\n", s);
std::printf("\t[%-10s]\n", s);
std::printf("\t[%*s]\n", 10, s);
std::printf("\t[%-10.*s]\n", 4, s);
std::printf("\t[%-*.*s]\n", 10, 4, s);
std::printf("Characters:\t%c %%\n", 'A');
std::printf("Integers:\n");
std::printf("\tDecimal: \t%i %d %.6i %i %.0i %+i %i\n",
1, 2, 3, 0, 0, 4,-4);
std::printf("\tHexadecimal:\t%x %x %X %#x\n",
5,10,10, 6);
std::printf("\tOctal: \t%o %#o %#o\n",
10, 10, 4);
std::printf("Floating point:\n");
std::printf("\tRounding:\t%f %.0f %.32f\n", 1.5, 1.5, 1.3);
std::printf("\tPadding:\t%05.2f %.2f %5.2f\n", 1.5, 1.5, 1.5);
std::printf("\tScientific:\t%E %e\n", 1.5, 1.5);
std::printf("\tHexadecimal:\t%a %A\n", 1.5, 1.5);
std::printf("\tSpecial values:\t0/0=%g 1/0=%g\n", 0.0/0.0, 1.0/0.0);
std::printf("Variable width control:\n");
std::printf("\tright-justified variable width: '%*c'\n", 5, 'x');
int r = std::printf("\tleft-justified variable width : '%*c'\n", -5, 'x');
std::printf("(the last printf printed %d characters)\n", r);
std::printf("Fixed-width types:\n");
std::uint32_t val = std::numeric_limits<std::uint32_t>::max();
std::printf("\tLargest 32-bit value is %" PRIu32 " or %#" PRIx32 "\n",
val, val);
}