CS 3 (Spring 2024) sprintf

Name

sprintf - formatted output conversion

Synopsis

#include <stdio.h>

int sprintf(char *str, const char *format, ...);

Description

The sprintf() function shall place output followed by the null byte, ‘\0’ , in consecutive bytes starting at *s; it is the user’s responsibility to ensure that enough space is available.

This function writes the output under the control of a format string that specifies how subsequent arguments are converted for output.</p>

The format string is a character string, beginning and ending in its initial shift state, if any. The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments. Each conversion specification is introduced by the character %, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width, an optional precision and an optional length modifier.

A character that specifies the type of conversion to be applied. The conversion specifiers and their meanings are:

d
The int argument is converted to signed decimal notation.
u, x
The unsigned int argument is converted to unsigned decimal (u), or unsigned hexadecimal (x) notation. The letters abcdef are used for x conversions.
f
The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.
c
The int argument is converted to an unsigned char, and the resulting character is written.
s
The const char * argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not including) a terminating null byte ('\0');
%
A '%' is written. No argument is converted. The complete conversion specification is '%%'.

The character % is followed by zero or more of the following flags:

0
The value should be zero padded. For d, u, x, and f conversions, the converted value is padded on the left with zeros rather than blanks. For other conversions, the behavior is undefined.

An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left

Return Value

Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).