The sprintf function is the same as printf except that it does not print
the result of the conversion but returns it as a string. Of course, if the trailing
semicolon at end of the sprintf command is not present, then the returned
string is still printed.
>> s = sprintf("e = %g, pi = %g\n", e, pi);
>> s
e = 2.71828, pi = 3.14159
Normal characters contained in the format string are printed literally, such as
the strings e = and pi = and \n. Each substring in
the format that starts with the character % and ends with a conversion
character is called a conversion specification. Valid conversion characters
include d, f, g, etc.. For example, in the format
k = %5d, e = %g, pi = %g\n,
%5d and
%g are conversion specifications, and the rest are normal characters.
Between the % sign and the type character there may be, in order,
- Flags (in no particular order), which modify the print specification
- -: left adjustment.
- +: the number will be printed with a sign.
- space: if the first character is not a sing, a space will be prefixed.
- 0: fields for numbers are padded with leading zeros.
- #: number will be printed in alternate form. For type o, the
printed number starts with zero. For x or X, the number
printed starts with 0x. Floating point numbers will always contain
the decimal point. And trailing zeros in format g are kept.
- Minimum field width This is an integer w. It specifies that the converted value
will be printed in at least w characters. If the value is shorter than
w characters, the field width will padded left or right (depending on
if left adjustment flag is present) with space or zeros (if zero flag is given).
- A period that separates the minimum field width and the precision.
- Precision This is an integer p. For
- strings: at most p characters will be printed
- integers: at least p digits will be printed (leading zeros might
be added)
- e,E,f conversions: p digits after the decimal point will
be printed
- g,G conversions: p significant digits will
be printed
- A length modifier l, L, or h, which indicate that
the corresponding numbers are to be printed as long, long
double, and short respectively. For definitions of these types please
refer to a C standard library manual.
The following is a list of the conversions that the functions of the
printf family can perform.
Character |
Type of Value |
d,i |
integer of signed decimal format |
o |
integer of unsigned octal format |
x,X |
integer of unsigned hexadecimal format |
u |
integer of unsigned decimal format |
c |
ASCII character |
s |
character string |
f |
floating point number of double precision, decimal notation |
e,E |
floating point number of double precision, scientific notation |
g,G |
floating point number of double precision; scientific notation if
size of exponent is too big, decimal notation otherwise. |
% |
print a % |
oz
2009-12-22