viernes, 2 de febrero de 2018

Formateando la salida con printf en matlab u octave - PRINTF - formatted output to standard output.

Ejemplos prácticos:

octave:11> printf('%6.4f', pi)
3.1416 
 
octave:12> printf('%*.*f', 6, 4, pi)
3.1416 
 
octave:13> printf('%.6d',20)
000020


octave:14> fprintf('%.6d',20);
000020



https://www.gnu.org/software/octave/doc/v4.2.1/Table-of-Output-Conversions.html

14.2.7 Table of Output Conversions

Here is a table summarizing what all the different conversions do:
%d’, ‘%i
Print an integer as a signed decimal number. See Integer Conversions, for details. ‘%d’ and ‘%i’ are synonymous for output, but are different when used with scanf for input (see Table of Input Conversions).
%o
Print an integer as an unsigned octal number. See Integer Conversions, for details.
%u
Print an integer as an unsigned decimal number. See Integer Conversions, for details.
%x’, ‘%X
Print an integer as an unsigned hexadecimal number. ‘%x’ uses lowercase letters and ‘%X’ uses uppercase. See Integer Conversions, for details.
%f
Print a floating-point number in normal (fixed-point) notation. See Floating-Point Conversions, for details.
%e’, ‘%E
Print a floating-point number in exponential notation. ‘%e’ uses lowercase letters and ‘%E’ uses uppercase. See Floating-Point Conversions, for details.
%g’, ‘%G
Print a floating-point number in either normal (fixed-point) or exponential notation, whichever is more appropriate for its magnitude. ‘%g’ uses lowercase letters and ‘%G’ uses uppercase. See Floating-Point Conversions, for details.
%c
Print a single character. See Other Output Conversions.
%s
Print a string. See Other Output Conversions.
%%
Print a literal ‘%’ character. See Other Output Conversions.
If the syntax of a conversion specification is invalid, unpredictable things will happen, so don’t do this. In particular, MATLAB allows a bare percentage sign ‘%’ with no subsequent conversion character. Octave will emit an error and stop if it sees such code. When the string variable to be processed cannot be guaranteed to be free of potential format codes it is better to use the two argument form of any of the printf functions and set the format string to %s. Alternatively, for code which is not required to be backwards-compatible with MATLAB the Octave function puts or disp can be used.
printf (strvar);        # Unsafe if strvar contains format codes
printf ("%s", strvar);  # Safe
puts (strvar);          # Safe
If there aren’t enough function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are unpredictable. If you supply more arguments than conversion specifications, the extra argument values are simply ignored; this is sometimes useful.

https://www.thinkage.ca/english/gcos/expl/nsc/lib/printf.html



https://la.mathworks.com/help/matlab/matlab_prog/formatting-strings.html

Formatting Text

To convert data to text and control its format, you can use formatting operators with common conversion functions, such as num2str and sprintf. These operators control notation, alignment, significant digits, and so on. They are similar to those used by the printf function in the C programming language. Typical uses for formatted text include text for display and output files.
For example, %f converts floating-point values to text using fixed-point notation. Adjust the format by adding information to the operator, such as %.2f to represent two digits after the decimal mark, or %12f to represent 12 characters in the output, padding with spaces as needed.
A = pi*ones(1,3);
txt = sprintf('%f | %.2f | %12f', A)
txt = 
'3.141593 | 3.14 |     3.141593'
You can combine operators with ordinary text and special characters in a format specifier. For instance, \n inserts a newline character.
txt = sprintf('Displaying pi: \n %f \n %.2f \n %12f', A)
txt = 
    'Displaying pi: 
      3.141593 
      3.14 
          3.141593'

Functions that support formatting operators are compose, num2str, sprintf, fprintf, and the error handling functions assert, error, warning, and MException.

Fields of the Formatting Operator

A formatting operator can have six fields, as shown in the figure. From right to left, the fields are the conversion character, subtype, precision, field width, flags, and numeric identifier. (Space characters are not allowed in the operator. They are shown here only to improve readability of the figure.) The conversion character is the only required field, along with the leading % character.

Conversion Character

The conversion character specifies the notation of the output. It consists of a single character and appears last in the format specifier.
SpecifierDescription
cSingle character.
dDecimal notation (signed).
eExponential notation (using a lowercase e, as in 3.1415e+00).
EExponential notation (using an uppercase E, as in 3.1415E+00).
fFixed-point notation.
gThe more compact of %e or %f. (Insignificant zeroes do not print.)
GSame as %g, but using an uppercase E.
oOctal notation (unsigned).
sCharacter vector or string array.
uDecimal notation (unsigned).
xHexadecimal notation (unsigned, using lowercase letters af).
XHexadecimal notation (unsigned, using uppercase letters AF).
For example, format the number 46 using different conversion characters to display the number in decimal, fixed-point, exponential, and hexadecimal formats.
A = 46*ones(1,4);
txt = sprintf('%d   %f   %e   %X', A)
txt = 
'46   46.000000   4.600000e+01   2E'

Subtype

The subtype field is a single alphabetic character that immediately precedes the conversion character. Without the subtype field, the conversion characters %o, %x, %X, and %u treat input data as integers. To treat input data as floating-point values instead and convert them to octal, decimal, or hexadecimal representations, use one of following subtype specifiers.
bThe input data are double-precision floating-point values rather than unsigned integers. For example, to print a double-precision value in hexadecimal, use a format like %bx.
tThe input data are single-precision floating-point values rather than unsigned integers.

Precision

The precision field in a formatting operator is a nonnegative integer that immediately follows a period. For example, in the operator %7.3f, the precision is 3. For the %g operator, the precision indicates the number of significant digits to display. For the %f, %e, and %E operators, the precision indicates how many digits to display to the right of the decimal point.
Display numbers to different precisions using the precision field.
txt = sprintf('%g   %.2g   %f   %.2f', pi*50*ones(1,4))
txt = 
'157.08   1.6e+02   157.079633   157.08'
While you can specify the precision in a formatting operator for input text (for example, in the %s operator), there is usually no reason to do so. If you specify the precision as p, and p is less than the number of characters in the input text, then the output contains only the first p characters.

Field Width

The field width in a formatting operator is a nonnegative integer that specifies the number of digits or characters in the output when formatting input values. For example, in the operator %7.3f, the field width is 7.
Specify different field widths. To show the width for each output, use the | character. By default, the output text is padded with space characters when the field width is greater than the number of characters.
txt = sprintf('|%e|%15e|%f|%15f|', pi*50*ones(1,4))
txt = 
'|1.570796e+02|   1.570796e+02|157.079633|     157.079633|'
When used on text input, the field width can determine whether to pad the output text with spaces. If the field width is less than or equal to the number of characters in the input text, then it has no effect.
txt = sprintf('%30s', 'Pad left with spaces')
txt = 
'          Pad left with spaces'

Flags

Optional flags control additional formatting of the output text. The table describes the characters you can use as flags.
CharacterDescriptionExample
Minus sign (-)Left-justify the converted argument in its field.%-5.2d
Plus sign (+)For numeric values, always print a leading sign character (+ or -).
For text values, right-justify the converted argument in its field.
%+5.2d
%+5s
Space ( )Insert a space before the value.% 5.2f
Zero (0)Pad with zeroes rather than spaces.%05.2f
Pound sign (#)Modify selected numeric conversions:
  • For %o, %x, or %X, print 0, 0x, or 0X prefix.
  • For %f, %e, or %E, print decimal point even when precision is 0.
  • For %g or %G, do not remove trailing zeroes or decimal point.
%#5.0f

Right- and left-justify the output. The default behavior is to right-justify the output text.
txt = sprintf('right-justify: %12.2f\nleft-justify: %-12.2f',...
              12.3, 12.3)
txt = 
    'right-justify:        12.30
     left-justify: 12.30       '

Display a + sign for positive numbers. The default behavior is to omit the leading + sign for positive numbers.
txt = sprintf('no sign: %12.2f\nsign: %+12.2f',...
              12.3, 12.3)
txt = 
    'no sign:        12.30
     sign:       +12.30'

Pad to the left with spaces and zeroes. The default behavior is to pad with spaces.
txt = sprintf('Pad with spaces: %12.2f\nPad with zeroes: %012.2f',...
              5.2, 5.2)
txt = 
    'Pad with spaces:         5.20
     Pad with zeroes: 000000005.20'

Note

You can specify more than one flag in a formatting operator.

Value Identifiers

By default, functions such as sprintf insert values from input arguments into the output text in sequential order. To process the input arguments in a nonsequential order, specify the order using numeric identifiers in the format specifier. Specify nonsequential arguments with an integer immediately following the % sign, followed by a $ sign.
Ordered SequentiallyOrdered By Identifier
sprintf('%s %s %s',...
        '1st','2nd','3rd')

ans =

    '1st 2nd 3rd'
sprintf('%3$s %2$s %1$s',...
        '1st','2nd','3rd')

ans =

    '3rd 2nd 1st'

Special Characters

Special characters can be part of the output text. But because they cannot be entered as ordinary text, they require specific character sequences to represent them. To insert special characters into output text, use any of the character sequences in the table.
Special CharacterRepresentation in Format Specifier
Single quotation mark''
Percent character%%
Backslash\\
Alarm\a
Backspace\b
Form feed\f
New line\n
Carriage return\r
Horizontal tab\t
Vertical tab\v
Character whose Unicode® numeric value can be represented by the hexadecimal number, N\xN
Example: sprintf('\x5A') returns 'Z'
Character whose Unicode numeric value can be represented by the octal number, N\N
Example: sprintf('\132') returns 'Z'

Setting Field Width and Precision

The formatting operator follows a set of rules for formatting output text to the specified field width and precision. You also can specify values for the field width and precision outside the format specifier, and use numbered identifiers with the field width and precision.

Rules for Formatting Precision and Field Width

The figure illustrates how the field width and precision settings affect the output of the formatting functions. In this figure, the zero following the % sign in the formatting operator means to add leading zeroes to the output text rather than space characters.
  • If the precision is not specified, then it defaults to six.
  • If the precision p is less than the number of digits in the fractional part of the input, then only p digits are shown after the decimal point. The fractional value is rounded in the output.
  • If the precision p is greater than the number of digits f in the fractional part of the input, then p digits are shown after the decimal point. The fractional part is extended to the right with p-f zeroes in the output.
  • If the field width is not specified, then it defaults to p+1+n, where n is the number of digits in the whole part of the input value.
  • If the field width w is greater than p+1+n, then the whole part of the output value is padded to the left with w-(p+1+n) additional characters. The additional characters are space characters unless the formatting operator includes the 0 flag. In that case, the additional characters are zeroes.

Specify Field Width and Precision Outside Format Specifier

You can specify the field width and precision using values from a sequential argument list. Use an asterisk (*) in place of the field width or precision fields of the formatting operator.
For example, format and display three numbers. In each case, use an asterisk to specify that the field width or precision come from input arguments that follow the format specifier.
txt = sprintf('%*f   %.*f   %*.*f',...
              15,123.45678,...     
              3,16.42837,...       
              6,4,pi)
txt = 
'     123.456780   16.428   3.1416'
The table describes the effects of each formatting operator in the example.
Formatting OperatorDescription
%*fSpecify width as the following input argument, 15.
%.*fSpecify precision as the following input argument, 3.
%*.*fSpecify width and precision as the following input arguments, 6, and 4.
You can mix the two styles. For example, get the field width from the following input argument and the precision from the format specifier.
txt = sprintf('%*.2f', 5, 123.45678)
txt = 
'123.46'

Specify Numbered Identifiers in Width and Precision Fields

You also can specify field width and precision as values from a nonsequential argument list, using an alternate syntax shown in the figure. Within the formatting operator, specify the field width and precision with asterisks that follow numbered identifiers and $ signs. Specify the values of the field width and precision with input arguments that follow the format specifier.
For example, format and display three numbers. In each case, use a numbered identifier to specify that the field width or precision come from input arguments that follow the format specifier.
txt = sprintf('%1$*4$f   %2$.*5$f   %3$*6$.*7$f',...
              123.45678, 16.42837, pi, 15, 3, 6, 4)
txt = 
'     123.456780   16.428   3.1416'
The table describes the effect of each formatting operator in the example.
Formatting OperatorDescription
%1$*4$f1$ specifies the first input argument, 123.45678, as the value
*4$ specifies the fourth input argument, 15, as the field width
%2$.*5$f2$ specifies the second input argument, 16.42837, as the value
.*5$ specifies the fifth input argument, 3, as the precision
%3$*6$.*7$f3$ specifies the third input argument, pi, as the value
*6$ specifies the sixth input argument, 6, as the field width
.*7$ specifies the seventh input argument, 4, as the precision

Restrictions on Using Identifiers

If any of the formatting operators include an identifier field, then all the operators in the format specifier must include identifier fields. If you use both sequential and nonsequential ordering in the same function call, then the output is truncated at the first switch between sequential and nonsequential identifiers.
Valid SyntaxInvalid Syntax
sprintf('%d %d %d %d',...
        1,2,3,4)

ans =

    '1 2 3 4'
sprintf('%d %3$d %d %d',...
        1,2,3,4)

ans =

    '1 '
If your function call provides more input arguments than there are formatting operators in the format specifier, then the operators are reused. However, only function calls that use sequential ordering reuse formatting operators. You cannot reuse formatting operators when you use numbered identifiers.
Valid SyntaxInvalid Syntax
sprintf('%d',1,2,3,4)

ans =

    '1234'
sprintf('%1$d',1,2,3,4)

ans =

    '1'
If you use numbered identifiers when the input data is a vector or array, then the output does not contain formatted data.
Valid SyntaxInvalid Syntax
v = [1.4 2.7 3.1];
sprintf('%.4f %.4f %.4f',v)

ans =

    '1.4000 2.7000 3.1000'
v = [1.4 2.7 3.1];
sprintf('%3$.4f %1$.4f %2$.4f',v)

ans =

  1×0 empty char array

See Also

| | |

 

PRINTF - formatted output to standard output.

(ANSI Standard)

Usage:

#include <stdio.h>
Nout = printf(format[,arg1,arg2,...]);

Where:

const char *format;
tells how to format the various arguments (see below).
arg1,arg2,...
is a variable argument list of expressions whose values should be printed according to the placeholders in the "format" string. If there are more placeholders than supplied arguments, the result is undefined. If there are more arguments than placeholders, the excess arguments are simply ignored.

Description:

"printf" writes formatted output to "stdout". The result of "printf" is the number of characters written. If a write error occurs, "printf" returns a negative number.
The output is formatted according to the "format" string. This string may contain two kinds of objects:
  • ordinary characters which are simply copied to "stdout";
  • placeholders, which tell "printf" how to format arguments in the variable argument list.
Each placeholder starts with the character '%' and ends with one or two letters that indicate what "type" of formatting is necessary. Between the '%' and the "type" field may appear "modifiers", "width", and "precision" fields. An ANSI placeholder has the form
%[modifiers][width][.precision]type
where square brackets indicate that a field is optional.
Because '%' has a special meaning to "printf", you must use two of them to stand for a literal per cent character. For example, you would use
printf("We had 100%% attendance!\n");
to print out the line
We had 100% attendance!

The Type Field

Below we list the recognized "type" fields. Note that each "type" requires that the output value associated with the placeholder have a particular data type. Note also that the standard rules for passing arguments in a variable argument list automatically convert "char" and "short" values to "int", and "float" values to "double", so "char", "short", and "float" arguments are not possible.
c
"int" argument is converted to "unsigned char", and then output. Note that this only writes a single character, even if the original "int" value held more than one character.
d
"int" argument is output as a signed decimal integer. If the number is positive, a '+' sign may or may not be output, depending on the value of the modifiers field.
e
"double" argument is output in scientific notation
[-]m.nnnnnne+xx
with one digit before the decimal point. The default number of digits after the decimal point is six, but this can be changed with a precision field. The "double" value is rounded to the correct number of decimal places. The exponent always contains two digits.
E
same as "%e" format, except that the 'E' will be in upper case instead of lower.
f
"double" argument is output in conventional form, i.e.
[-]mmmm.nnnnnn
The default number of digits after the decimal point is six, but this can be changed with a precision field. If a decimal point appears, at least one digit appears before it. The "double" value is rounded to the correct number of decimal places.
g
"double" argument is output in scientific or standard format. Scientific notation is only used if the exponent resulting from the conversion is less than -4 or greater than the precision; otherwise standard representation is used. With scientific notation, the 'e' to mark the exponent is in lower case. The precision is taken to mean the number of significant digits required (not necessarily the number of decimal places). Trailing zeros are removed from the result, and a decimal point only appears if it is followed by a digit.
G
same as "%g" format, except that the 'E' to mark the exponent in scientific notation is in upper case.
i
same as "%d".
n
"(int *)" argument is taken to point to integer. "printf" assigns this integer the number of characters that have been written to the output stream so far by this call to "printf". No output is written for this placeholder.
o
"int" argument is output as an unsigned integer written with octal digits. This will not have a leading zero, unless the # "modifier" is used (see below).
p
corresponding argument is assumed to be "(const void *)" value. The value of the pointer is converted to a sequence of printable characters in an implementation-defined manner. NS mode C displays the value of the pointer as an octal integer.
s
"(const char *)" argument is taken as pointer to ASCII string. Characters in this string will be output until a '\0' character is found or the number of characters indicated by the precision field has been printed.
u
"int" argument is output as an unsigned decimal integer.
x
"int" argument is output as an unsigned integer written with hexadecimal digits, using the letters 'a' to 'f' for hex digits greater than 9. This will not have a leading '0x' unless the # "modifier" is used (see below).
X
same as "%x" except that the letters 'A' to 'F' are used for hex digits greater than 9.
hd
same as "%d" except that "int" argument is converted to "short" before formatting and printing. Since "short" is the same as "int" on the DPS-8, this is the same as "%d".
hi
same as "%hd".
ho
same as "%o" except that the "int" argument is converted to "unsigned short" before formatting and printing. Since "unsigned short" is the same as "unsigned" on the DPS-8, this is the same as "%o".
hu
same as "%u" except that the "int" argument is converted to "unsigned short" before formatting and printing. Since "unsigned short" is the same as "unsigned" on the DPS-8, this is the same as "%u".
hx
same as "%x" except that the "int" argument is converted to "unsigned short" before formatting and printing. Since "unsigned short" is the same as "unsigned" on the DPS-8, this is the same as "%x".
hX
same as "%X" except that the "int" argument is converted to "unsigned short" before formatting and printing. Since "unsigned short" is the same as "unsigned" on the DPS-8, this is the same as "%X".
ld
same as "%d" except argument is "long" integer. Since "long" is the same as "int" on the DPS-8, this is the same as "%d". However, the compiler will warn you if you specify "%ld" but pass a normal "int", or specify "%d" but pass a "long". Similar warnings are issued for all the other "%l" placeholders described below.
li
same as "%ld".
lo
same as "%o" except argument is "unsigned long" integer. Since "unsigned long" is the same as "unsigned" on the DPS-8, this is equivalent to "%o".
lu
same as "%u" except argument is "unsigned long" integer. Since "unsigned long" is the same as "unsigned" on the DPS-8, this is equivalent to "%u".
lx
same as "%x" except argument is "unsigned long" integer. Since "unsigned long" is the same as "unsigned" on the DPS-8, this is equivalent to "%x".
lX
same as "%X" except argument is "unsigned long" integer. Since "unsigned long" is the same as "unsigned" on the DPS-8, this is equivalent to "%X".
Le
same as "%e" except argument is "long double". Since "long double" is the same as "double" on the DPS-8, this is the same as "%e".
LE
same as "%E" except argument is "long double". Since "long double" is the same as "double" on the DPS-8, this is the same as "%E".
Lf
same as "%f" except argument is "long double". Since "long double" is the same as "double" on the DPS-8, this is the same as "%f".
Lg
same as "%g" except argument is "long double". Since "long double" is the same as "double" on the DPS-8, this is the same as "%g".
LG
same as "%G" except argument is "long double". Since "long double" is the same as "double" on the DPS-8, this is the same as "%G".
The types that have just been listed are recognized by the ANSI standard. In addition to these, this version of C supports a number of extensions.
_a
"(const char *)" argument taken as pointer to an ASCII string. The string is printed out using escape sequences for all non-printable characters. Escape sequences are also used for special characters like the backslash, single, and double quotes. The format is such that the output could be a valid ASCII string literal if it were enclosed in double quotes. If you specify the '-' modifier, output will be left-justified; otherwise, it will be right-justified. If you specify the '+' modifier, '\0' characters will not be considered to be the end of the string; in this case, a precision must be specified to tell "printf" how many characters to print.
_c
"int" argument is taken to contain BCD characters. These are output as their ASCII equivalents; letters are output in lower case. If you specify a precision of zero, PRINTF will strip off high order zeroes at the beginning of the argument word and interpret the rest as BCD characters. If you specify a width, the precision is automatically set to the same value. If you do not specify either a precision or width, the default is "%6.0_c".
_C
is the same as "%_c", except that letters are output in upper case.
_e
"double" argument is output in scientific notation. This is almost like "%e", except that the width field takes precedence over the precision. Thus if the requested width is too small to provide the requested precision, a smaller precision will be used.
_E
same as "%_e" format except that the 'E' for the exponent will be in upper case instead of lower.
_f
"double" argument is output in "optimal" format. If the specified width is sufficient to hold the value with the requested precision in standard format (nnn.nnn), the value will be printed in standard format. If the width is not sufficient, "printf" will use either standard format or scientific notation, whichever provides the requested precision with the fewer characters. If no width or precision is specified, the number will be output with the greatest available precision. If a width is specified, but not a precision, the number will be rounded to the appropriate width. If the fractional part of the number is zero, no zeros will be printed after the decimal place. Thus there is a difference between
1.
1.000000
The first number is a true 1.0. The second is not 1.0, but has a fractional part that is too small to show in the given precision. When scientific notation is used, the 'e' to mark the exponent is in lower case.
_F
same as "%_f", except that when scientific notation is used, the 'E' to mark the exponent is in upper case.
_g
same as "%_f" format, except that the precision is interpreted as the number of significant digits, not the number of decimal places. This means that very small numbers will be printed in scientific notation instead of rounded to a .000000 form. When scientific notation is used, the 'e' to mark the exponent is in lower case.
_G
same as "%_g" format, except that when scientific notation is used, the 'E' to mark the exponent is in upper case.
_s
"(void *)" argument is taken as a BCD pointer. See "expl nsc lib _bcdptr" for more on BCD pointers. If only a width is specified, the string will be assumed to have that number of BCD characters, and the corresponding ASCII characters are output (with letters in lower case and trailing blanks removed). If a width and a precision field are specified, the precision is taken to be the number of BCD characters in the string and the width is the size of the output field. If no width is given, the default is six. Trailing blanks are stripped, unless the '#' modifier is specified. By default, the output is right-justified; if the modifier '-' is given, the output will be left-justified.
_S
same as "%_s" except that letters are output in upper case.
_v
has two corresponding arguments: a "const char *" format string in the same format as a normal "printf" format string; and a "va_list" argument, as declared in <stdarg.h>. The "va_list" argument is presumed to indicate all or part of a variable argument list (i.e. the argument has been set up with "va_start"). The arguments remaining in this variable argument list are formatted and output according to the given format string. For more information on variable argument lists, see "expl nsc include stdarg".

The Modifiers Field

The modifiers field consists of zero or more characters that indicate how output should be padded (e.g. whether numbers are preceded by blanks or leading zeros), and whether or not '+' or '-' signs are printed. Below we list the possible "modifier" characters.
- (minus)
indicates that values should be left-justified in the output field. The default action is to right-justify them.
+ (plus)
is relevant only for signed numeric output values and "%_a". This "modifier" character tells "printf" to put a sign in front of the number, whether or not it is negative. Thus negative numbers will be preceded by '-' while zero and positive numbers will be preceded by '+'. The default is to add the sign only if the number is negative. See the description of "%_a" for the effect of '+' with that placeholder.
  (blank)
is relevant only for signed numeric output values. This "modifier" character tells "printf" to put a sign in front of numbers only if they are negative. If the number is non-negative, "printf" will put in a blank instead of a sign. The default is not to put a blank in front of non-negative number. If both '+' and ' ' are specified as "modifier" characters, the '+' overrides the ' '.
# (sharp)
is relevant only for some output types. If "type" is 'o', all non-zero values will have a leading 0; normally, octal output has no leading zero.
If "type" is 'x' or 'X', all non-zero values will have a leading 0x or 0X respectively; normally, such prefixes are omitted.
If "type" is 'e', 'E' or 'f', "printf" will always print out a decimal point (normally, the decimal point is omitted if the number has no fractional part).
If "type" is '_f', trailing zeros are printed after a decimal point, even if the fractional part of the number is zero.
If "type" is 'g' or 'G', "printf" will always print out a decimal point and trailing zeros will not be removed; usually 'g' and 'G' remove trailing zeros.
If "type" is '_s' or '_S', trailing blanks are not trimmed.
If "type" is '_a', the output is enclosed in double quotes.

The Width Field

The width field is a non-negative decimal integer giving the minimum number of characters to be printed. If the output value is shorter than the given width, it is padded to the appropriate width by putting blanks on the right (or on the left, if the '-' "modifier" character is specified).
With numeric placeholders, the number in the width field may have a leading 0. With this, the output value will be expanded with zeros to give the number the specified width. For example, with "%05d" the value -1 will be printed as "-0001".
The width field can also be the character '*', in which case "printf" will take the next argument in the argument list and take that as the width value. For example,
printf("%*d",4,X);
prints the value of X with a width of 4. Note that the width value is obtained from the argument list BEFORE the output value is obtained.
The width field specifies the MINIMUM number of characters to be output. If more characters are needed, the output will be wider than width (unless the precision value dictates otherwise).

The Precision Field

The precision field is a dot '.' followed by a non-negative decimal integer. Its meaning depends on the "type" field as given below.
  • If the "type" is 'd', 'o', 'u', 'x' or 'X', the precision number is the smallest number of digits that may appear in the output value. If necessary, the number will be padded on the left with leading zeros. If the precision number is 0 or the field is just a '.' with no number following, an output value of 0 will result in no characters being printed.
  • If the "type" is 'e', 'E', or 'f', the precision number is the number of digits printed after the decimal point. If the precision number is 0 or the field is just a '.' with no number following, no decimal point is printed.
  • If the "type" is 'g' or 'G', the precision number is the maximum number of significant digits to be printed. If no precision field is specified, six significant digits are printed.
  • If the "type" is 's', the precision number gives the maximum number of characters to be printed.
  • If the "type" is an 'h', 'l' or 'L' type, the precision field has the same effect as it has for the type without the 'h', 'l' or 'L'.
  • If the "type" is "_e", "_E", "_f", or "_F", the precision number is the number of digits printed after the decimal point. If no precision is specified, the width will dictate the precision. If no width is specified either, the value will be printed to full precision.
  • If the "type" is "_g" or "_G", the precision is the maximum number of significant digits to be printed. If no precision field is specified, all significant digits are printed.
The precision field can also be the character '*', in which case "printf" will take the next argument in the argument list and take that as the precision value. For example,
printf("%*.*f",8,3,Y);
prints the value of Y with a width of 8 and a precision of 3.

Fill Characters

As a non-ANSI extension, all placeholders may specify a "fill character" by putting ",F" in front of the type designator (where F is any character). In any situation where "printf" would normally fill out a field with blanks, the fill character will be used instead. For example, with
printf("%5,#d",20);
the output would be
###20
The "#" after the comma is used as a fill character.
As with width and precision, the fill field can also be the character '*', in which case "printf" will take the next argument in the argument list and take that as the fill value. For example,
printf("%,*d",'*',20);
will fill with asterisks. If you want to fill with asterisks, you have to take this approach.

Defaults

Below we list the defaults when width and/or precision fields are omitted.
"%1c"     "%1.1d"    "%11.6e"   "%11.6E"
"%8.6f"   "%1.6g"    "%1.6G"    "%1.1o"
"%0s"     "%1.1x"    "%1.1X"    "%1.1ld"
"%1.1lo"  "%1.1lx"   "%1.1lX"   "%6.6Le"
"%6.6LE"  "%6.6Lf"   "%6.6Lg"   "%6.6LG"

Examples:

#include <stdio.h>
int i = 3, j = -1, k = 4;
char *s = "string";
float x = 3.14159265;
printf("j = %.*d, %.3s x = %10.*f",i,j,s,k,x);
/* prints:  j = -001, str x =     3.1416 */
In the next examples, we use the letter 'b' to show where spaces are printed out. In all cases, the value printed is the integer -1.
Format     Output
 %5d       bbb-1
 %05d      -0001
 %5.5d     -00001 (precision requires 5 sig. digits)
 %5,0d     000-1  (zero is fill character)

Notes:

The "printf" function does almost no validity checking on the format string. Therefore, if you specify an invalid format, you will probably get invalid output without any diagnostic message. You may also get more serious errors (e.g. memory faults).
Most users will find that "%g" is the best format for printing out single floating point numbers, since it tries to choose the most readable format. For columns of floating point numbers, "%_f" is usually better than "%f" because "%_f" makes more of an effort to provide the precise width requested (or as close as possible to that width).

 

No hay comentarios:

Publicar un comentario