std::printf...td::snprintf(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– NAME πŸ’–

std::printf,std::fprintf,std::sprintf,std::snprintf - std::printf,std::fprintf,std::sprintf,std::snprintf

Okay bestie, this is the std::printf...td::snprintf(3) page from the C++ Standard Libary β€” yes, the header really says β€œLibary,” and we are keeping the lore. πŸ’…


✨ Synopsis ✨

Defined in header <cstdio>:

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, ... );

The vibe check on those numbered overloads:

  1. (1) β€” printf
  2. (2) β€” fprintf
  3. (3) β€” sprintf
  4. (4) (since C++11) β€” snprintf

Loads the data from the given locations, converts them to character string equivalents and writes the results to a variety of sinks. Iconic behavior, honestly.

  1. Writes the results to stdout.
  2. Writes the results to a file stream stream.
  3. Writes the results to a character string buffer.
  4. Writes the results to a character string buffer. At most buf_size - 1 characters are written. The resulting character string will be terminated with a null character, unless buf_size is zero. If buf_size is zero, nothing is written and buffer may be a null pointer, however the return value (number of bytes that would be written not including the null terminator) is still calculated and returned.
⚠️ If a call to sprintf or snprintf causes copying to take place between objects that overlap, the behavior is undefined (e.g. sprintf(buf, "%s text", buf);). That is not a cute overlap. That is undefined behavior. Do not do it.

🌸 Parameters 🌸

  • stream β€” output file stream to write to
  • buffer β€” pointer to a character string to write to
  • buf_size β€” up to buf_size - 1 characters may be written, plus the null terminator
  • format β€” pointer to a null-terminated multibyte string specifying how to interpret the data
  • ... β€” arguments specifying data to print. If any argument after default conversions is not the type expected by the corresponding conversion specifier, 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

πŸ’… The format string: what’s the tea?

The format string consists of ordinary byte characters (except %), which are copied unchanged into the output stream, and conversion specifications. Each conversion specification has the following format:

  • introductory % character.
  • (optional) one or more flags that modify the behavior of the conversion:
    • -: the result of the conversion is left-justified within the field (by default it is right-justified).
    • +: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative).
    • space: if the result of a signed conversion does not start with a sign character, or is empty, space is prepended to the result. It is ignored if + flag is present.
    • #: alternative form of the conversion is performed. See the table below for exact effects otherwise the behavior is undefined.
    • 0: for integer and floating-point number conversions, leading zeros are used to pad the field instead of space characters. For integer numbers it is ignored if the precision is explicitly specified. For other conversions using this flag results in undefined behavior. It is ignored if - flag is present.
  • (optional) integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int, which appears before the argument to be converted and the argument supplying precision if one is supplied. If the value of the argument is negative, it results with the - flag specified and positive field width (Note: This is the minimum width: The value is never truncated.).
  • (optional) . followed by integer number or *, or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int, which appears before the argument to be converted, but after the argument supplying minimum field width if one is supplied. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is taken as zero. See the table below for exact effects of precision.
  • (optional) length modifier that specifies the size of the argument (in combination with the conversion format specifier, it specifies the type of the corresponding argument).
  • conversion format specifier.

The following format specifiers are available:

Length-modifier tea πŸ«–: the source table marks hh, ll, j, z, and t as (C++11).

% β€” the literal-percent era

  • What it does: Writes literal %. The full conversion specification must be %%.
  • Expected argument type by length modifier: hh: N/A; h: N/A; (none): N/A; l: N/A; ll: N/A; j: N/A; z: N/A; t: N/A; L: N/A.

c β€” one character, main character energy

  • What it does: Writes a single character. The argument is first converted to unsigned char. If the l modifier is used, the argument is first converted to a character string as if by %ls with a wchar_t[2] argument.
  • Expected argument type by length modifier: hh: N/A; h: N/A; (none): int; l: wint_t; ll: N/A; j: N/A; z: N/A; t: N/A; L: N/A.

s β€” character string slay

  • What it does: Writes a character string.

The argument must be a pointer to the initial element of an array of characters. Precision specifies the maximum number of bytes to be written. If Precision is not specified, writes every byte up to and not including the first null terminator. If the l specifier is used, the argument must be a pointer to the initial element of an array of wchar_t, which is converted to char array as if by a call to wcrtomb with zero-initialized conversion state.

  • Expected argument type by length modifier: hh: N/A; h: N/A; (none): char*; l: wchar_t*; ll: N/A; j: N/A; z: N/A; t: N/A; L: N/A.

d, i β€” signed decimal, no cap

  • What it does: Converts a signed integer into decimal representation [-]dddd.

Precision specifies the minimum number of digits to appear. The default precision is 1.

If both the converted value and the precision are 0 the conversion results in no characters.

  • Expected argument type by length modifier: hh: signed char; h: short; (none): int; l: long; ll: long long; j: intmax_t; z: signed size_t; t: ptrdiff_t; L: N/A.

o β€” unsigned octal moment

  • What it does: Converts an unsigned integer into octal representation oooo.

Precision specifies the minimum number of digits to appear. The default precision is 1. If both the converted value and the precision are 0 the conversion results in no characters. In the alternative implementation precision is increased if necessary, to write one leading zero. In that case if both the converted value and the precision are 0, single 0 is written.

  • Expected argument type by length modifier: hh: unsigned char; h: unsigned short; (none): unsigned int; l: unsigned long; ll: unsigned long long; j: uintmax_t; z: size_t; t: ptrdiff_t; L: N/A.

x, X β€” hexadecimal, lowercase vs uppercase

  • What it does: Converts an unsigned integer into hexadecimal representation hhhh.

For the x conversion letters abcdef are used. For the X version of conversion letters ABCDEF are used. Precision specifies the minimum number of digits to appear. The default precision is 1. If both the converted value and the precision are 0 the conversion results in no characters. In the alternative implementation 0x or 0X is prefixed to results if the converted value is nonzero.

  • Expected argument type by length modifier: hh: unsigned char; h: unsigned short; (none): unsigned int; l: unsigned long; ll: unsigned long long; j: uintmax_t; z: size_t; t: ptrdiff_t; L: N/A.

u β€” unsigned decimal, yes ma’am

  • What it does: Converts an unsigned integer into decimal representation dddd.

Precision specifies the minimum number of digits to appear. The default precision is 1. If both the converted value and the precision are 0 the conversion results in no characters.

  • Expected argument type by length modifier: hh: unsigned char; h: unsigned short; (none): unsigned int; l: unsigned long; ll: unsigned long long; j: uintmax_t; z: size_t; t: ptrdiff_t; L: N/A.

🌊 The next floating-point row (part 1 ends mid-row)

  • What it does so far: Converts floating-point number to the decimal notation in the style [-]ddd.ddd.
  • f, F β€” bestie, buckle in: Precision specifies the exact number of digits to appear after the decimal point character. The default precision is 6. In the alternative implementation, the decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style, see the notes below. (the argument-type cells in this row just read N/A across the board)
  • e, E β€” converts a floating-point number to the decimal exponent notation. Here's the tea: for the e conversion style, [-]d.dddeΒ±dd is used. For the E conversion style, [-]d.dddEΒ±dd is used. The exponent contains at least two digits, more digits are used only if necessary. If the value is 0, the exponent is also 0. Precision specifies the exact number of digits to appear after the decimal point character β€” default precision is 6. In the alternative implementation the decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style, see notes. (argument-type cells: N/A again, all of them)
  • a, A β€” converts a floating-point number to the hexadecimal exponent notation ✨. For the a conversion style, [-]0xh.hhhpΒ±d is used. For the A conversion style, [-]0Xh.hhhPΒ±d is used. The first hexadecimal digit is not 0 if the argument is a normalized floating-point value. If the value is 0, the exponent is also 0. Precision specifies the exact number of digits to appear after the hexadecimal point character. The default precision is sufficient for exact representation of the value. In the alternative implementation the decimal point character is written even if no digits follow it. For infinity and not-a-number conversion style, see notes. Argument types for this row: double, double (C++11), long double β€” and the leftover cells are N/A, N/A, N/A.
  • g, G β€” converts a floating-point number to decimal or decimal exponent notation, depending on the value and the precision. So for the g conversion style, conversion with style e or f will be performed; for the G conversion style, conversion with style E or F will be performed. Let P equal the precision if nonzero, 6 if the precision is not specified, or 1 if the precision is 0. Then, if a conversion with style E would have an exponent of X:
    • if P > X β‰₯ βˆ’4, the conversion is with style f or F and precision P βˆ’ 1 βˆ’ X.
    • otherwise, the conversion is with style e or E and precision P βˆ’ 1.

Unless alternative representation is requested, the trailing zeros are removed β€” and the decimal point character is removed too if no fractional part is left. For infinity and not-a-number conversion style, see notes. (argument-type cells: N/A, N/A, N/A, N/A, N/A, N/A β€” yeah, all of them)

  • n β€” returns the number of characters written so far by this call to the function πŸ’…. The result is written to the value pointed to by the argument. The specification may not contain any flag, field width, or precision (periodt, it's not that kind of specifier). Argument types: signed char*, short*, int*, long*, long long*, intmax_t*, size_t*, ptrdiff_t*, and N/A for the last one.
  • p β€” writes an implementation-defined character sequence defining a pointer. Argument type: void* β€” the rest of that row is N/A city.

okay so now the little block of notes that lives under the table, and honestly it's giving important 🫢:

The floating-point conversion functions convert infinity to inf or infinity. Which one is used is implementation defined.

Not-a-number is converted to nan or nan(char_sequence). Which one is used is implementation defined.

The conversions F, E, G, A output INF, INFINITY, NAN instead.

Even though %c expects an int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called. (we love automatic glow-ups ✨)

The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header <cinttypes> (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).

🚨 The memory-writing conversion specifier %n is a common target of security exploits where format strings depend on user input and is not supported by the bounds-checked printf_s family of functions. Like, do not mess with this one, bestie. fr fr.

There is a sequence point after the action of each conversion specifier; this permits storing multiple %n results in the same variable or, as an edge case, printing a string modified by an earlier %n within the same call.

If a conversion specification is invalid, the behavior is undefined. πŸ’€


πŸ’– Return value πŸ’–

  1. 1,2) Number of characters written if successful or a negative value if an error occurred.
  2. 3) Number of characters written if successful (not including the terminating null character) or a negative value if an error occurred.
  3. 4) Number of characters that would have been written for a sufficiently large buffer if successful (not including the terminating null character), or a negative value if an error occurred. Thus, the (null-terminated) output has been completely written if and only if the returned value is nonnegative and less than buf_size.

🌸 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 n<sup>th</sup> argument).

Calling std::snprintf with zero buf_size and a null pointer for buffer is useful (when the overhead of double-call is acceptable) to determine the necessary buffer size to contain the output:

auto fmt = "sqrt(2) = %f";
int sz = std::snprintf(nullptr, 0, fmt, std::sqrt(2));
std::vector<char> buf(sz + 1); // note +1 for null terminator
std::sprintf(buf.data(), fmt, std::sqrt(2)); // certain to fit

like, that's the "measure twice, allocate once" vibe and it ate πŸ”₯


πŸŽ€ Example πŸŽ€

// Run this code

#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);
}

go run it, the output is lowkey iconic πŸ¦‹

...and when you actually run it, the output is exactly this, bestie β€” spacing and all (yes the spacing matters, do not touch it πŸ’…):

        Strings:
                [     Hello]
                [Hello     ]
                [     Hello]
                [Hell      ]
                [Hell      ]
        Characters:     A %
        Integers:
                Decimal:        1 2 000003 0  +4 -4
                Hexadecimal:    5 a A 0x6
                Octal:          12 012 04
        Floating point:
                Rounding:       1.500000 2 1.30000000000000004440892098500626
                Padding:        01.50 1.50  1.50
                Scientific:     1.500000E+00 1.500000e+00
                Hexadecimal:    0x1.8p+0 0X1.8P+0
                Special values: 0/0=-nan 1/0=inf
        Variable width control:
                right-justified variable width: '    x'
                left-justified variable width : 'x    '
        (the last printf printed 41 characters)
        Fixed-width types:
                Largest 32-bit value is 4294967295 or 0xffffffff

Like, look at that 1.30000000000000004440892098500626 β€” that's the whole vibe of floating point right there, no notes 😭. And 0/0=-nan, 1/0=inf living their truth in the special values line 🫢.


πŸ‘€ See also πŸ‘€

Okay so here's the extended universe of this whole family, because std::printf did NOT come to play solo πŸ’–:

  • wprintf β€” prints formatted wide character output to stdout, a file stream or a buffer
  • fwprintf β€” same energy as above but it's a function
  • swprintf β€” also a function, also printing into buffers, you get the pattern by now
  • vprintf β€” the variadic sibling
  • vfprintf β€” prints formatted output to stdout, a file stream or a buffer using variable argument list
  • vsprintf β€” prints formatted output to stdout, a file stream or a buffer using variable argument list
  • vsnprintf β€” function, and it's marked (C++11)
  • fputs β€” writes a character string to a file stream (function)
  • scanf β€” reads formatted input from stdin, a file stream or a buffer
  • fscanf β€” function πŸŽ€
  • sscanf β€” function, the reading-into-a-string one
  • to_chars β€” converts an integer or floating-point value to a character sequence (C++17) (function)
  • print β€” prints to stdout or a file stream using formatted representation of the arguments (C++23) (function template)
  • println β€” same as std::print except that each print is terminated by additional new line (C++23) (function template)
  • C documentation for printf, fprintf, sprintf, snprintf

ngl if you got all the way here you're lowkey a formatting legend now πŸ‘‘ the sheer number of conversion specs you just survived is giving main character energy.

✨ okay bye bestie, this page came from http://cppreference.com, dated 2024.06.10, and it's the std::printf...td::snprintf(3) page β€” go forth and format slay πŸ’…πŸŒˆπŸ’–

πŸ“¦ where this page comes from