sprintf
Arguments:
String format, String source.
Result:
String.
Usage:
Forms a source in accordance with the provided format.
Format Specifier
The format parameter can contain format specifiers that begin with %
. These specifiers are replaced by the values of respective variables that follow the format string.
A format specifier has the following parts:
- A leading
%
sign - flags - one or more flags that modifies the conversion behavior (optional)
-
: Left justify the result within the field. By default it is right justified.+
: The sign of the result is attached to the beginning of the value, even for positive results.- space: If there is no sign, a space is attached to the beginning of the result.
#
: An alternative form of the conversion is performed.0
: It is used for integer and floating point numbers. Leading zeros are used to pad the numbers instead of space.
- width - an optional
*
or integer value used to specify minimum width field. - precision - an optional field consisting of a
.
followed by*
or integer or nothing to specify the precision. - length - an optional length modifier that specifies the size of the argument.
- specifier - a conversion format specifier.
The general prototype of format specifier for sprintf()
is:
%[flags][width][.precision][length]specifier
Commonly Used Format Specifiers
The table below lists some commonly used format specifiers:
Format Specifier | Description |
---|---|
% |
a % followed by another % character prints % to the screen |
c |
writes a single character |
s |
writes a character string |
d or i |
converts a signed integer to decimal representation |
o |
converts an unsigned integer to octal representation |
X or x |
converts an unsigned integer to hexadecimal representation |
u |
converts an unsigned integer to decimal representation |
F or f |
converts floating-point number to the decimal representation |
E or e |
converts floating-point number to the decimal exponent notation |
A or a |
converts floating-point number to the hexadecimal exponent |
G or g |
converts floating-point number to either decimal or decimal exponent notation |
n |
- returns the number of characters written so far - the result is written to the value pointed to by the argument - the argument must be a pointer to signed int |
p |
writes an implementation-defined character sequence defining a pointer |