printf

Description

Prints formatted output to the standard output stream.

#include <stdio.h>

int printf( const char *format [[, argument]]...);

format Format control  
argument Optional arguments  

Remarks

The printf function formats and prints a series of characters and values to the standard output stream, stdout. The format argument consists of ordinary characters, escape sequences, and (if arguments follow format) format specifications. The ordinary characters and escape sequences are copied to stdout in order of their appearance. For example, the line

printf("Line one\n\t\tLine two\n");

produces the output

Line one

Line two

If arguments follow the format string, the format string must contain specifications that determine the output format for the arguments.

Format specifications always begin with a percent sign (%) and are read left to right. When the first format specification (if any) is encountered, the value of the first argument after format is converted and output accordingly. The second format specification causes the second argument to be converted and output, and so on. If there are more arguments than there are format specifications, the extra arguments are ignored. The results are undefined if there are not enough arguments for all the format specifications.

Format Specification Fields

A format specification, which consists of optional and required fields, has the following form:

%[[flags]] [[width]] [[.precision]] [[{F | N | h | l | L}]]type

Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character (for example, %s). The optional fields, which appear before the type character, control other aspects of the formatting. The fields in a printf format specification are described in the following list:

Field Description  

type Required character that determines whether the associated argument is interpreted as a character, a string, or a number. (See Table R.2.)  
flags Optional character or characters that control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes. (See Table R.3.) More than one flag can appear in a format specification.  
width Optional number that specifies minimum number of characters output.  
precision Optional number that specifies maximum number of characters printed for all or part of the output field, or minimum number of digits printed for integer values. (See Table R.4.)  
F, N Optional prefixes that refer to the “distance” to the object being printed (near or far).  
  F and N are not part of the ANSI definition for printf. They are Microsoft extensions that should not be used if ANSI portability is desired.  
h, l, L Optional prefixes that determine the size of the argument expected, as shown below:  
  Prefix Use
  h Used with the integer types d, i, o, x, and X to specify that the argument is short int, or with u to specify short unsigned int. If used with %p, it indicates a 16-bit pointer.
  l Used with d, i, o, x, and X types to specify that the argument is long int, or with u to specify long unsigned int; also used with e, E, f, g, and G types to specify double rather than float. If used with %p, it indicates a 32-bit pointer.
  L Used with e, E, f, g, and G types to specify long double.

If a percent sign is followed by a character that has no meaning as a format field, the character is copied to stdout. For example, to print a percent-sign character, use %%.

Type Field Characters

The type character is the only required format field for the printf function; it appears after any optional format fields. The type character determines whether the associated argument is interpreted as a character, string, or number (see Table R.2).

Table R.2 Type Characters for printf

Character Type Output Format

d int Signed decimal integer.
i int Signed decimal integer.
u int Unsigned decimal integer.
o int Unsigned octal integer.
x int Unsigned hexadecimal integer, using “abcdef.”
X int Unsigned hexadecimal integer, using “ABCDEF.”
f double Signed value having the form [–]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
e double Signed value having the form [–]d.dddd e [sign]ddd, where d is a single decimal digit, dddd is one or more decimal digits, ddd is exactly three decimal digits, and sign is + or –.
E double Identical to the e format, except that E, rather than e, introduces the exponent.
g double Signed value printed in f or e format, whichever is more compact for the given value and precision. The e format is used only when the exponent of the value is less than –4 or greater than or equal to the precision argument. Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it.
G double Identical to the g format, except that G, rather than g, introduces the exponent (where appropriate).
c int Single character.
s String Characters printed up to the first null character ('\0') or until the precision value is reached.
n Pointer to integer Number of characters successfully written so far to the stream or buffer; this value is stored in the integer whose address is given as the argument.
p Far pointer to void Prints the address pointed to by the argument in the form xxxx:yyyy, where xxxx is the segment and yyyy is the offset, and the digits x and y are uppercase hexadecimal digits; %hp indicates a near pointer and prints only the offset of the address.

Flag Directives

The first optional field of the format specification is flag. A flag directive is a character that justifies output and prints signs, blanks, decimal points, and octal and hexadecimal prefixes. More than one flag directive may appear in a format specification. (See Table R.3.)

Table R.3 Flag Characters for printf

Flag Meaning Default

Left justify the result within the given field width. Right justify.
+ Prefix the output value with a sign (+ or –) if the output value is of a signed type. Sign appears only for negative signed values (–).
0 If width is prefixed with 0, zeros are added until the minimum width is reached. If 0 and - appear, the 0 is ignored. If 0 is specified with an integer format (i, u, x, X, o, d), the 0 is ignored. No padding.
blank (' ') Prefix the output value with a blank if the output value is signed and positive; the blank is ignored if both the blank and + flags appear. No blank appears.
# When used with the o, x, or X format, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively. No blank appears.
  When used with the e, E, or f format, the # flag forces the output value to contain a decimal point in all cases. Decimal point appears only if digits follow it.
  When used with the g or G format, the # flag forces the output value to contain a decimal point in all cases and prevents the truncation of trailing zeros. Decimal point appears only if digits follow it. Trailing zeros are truncated.
  Ignored when used with c, d, i, u, or s.,  

Width Specification

The second optional field of the format specification is the width specification. The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. If the number of characters in the output value is less than the specified width, blanks are added to the left or the right of the values—depending on whether the flag (for left justification) is specified—until the minimum width is reached. If width is prefixed with 0, zeros are added until the minimum width is reached (not useful for left-justified numbers).

The width specification never causes a value to be truncated. If the number of characters in the output value is greater than the specified width, or width is not given, all characters of the value are printed (subject to the precision specification).

The width specification may be an asterisk (*), in which case an int argument from the argument list supplies the value. The width argument must precede the value being formatted in the argument list. A nonexistent or small field width does not cause a truncation of a field; if the result of a conversion is wider than the field width, the field expands to contain the conversion result.

Precision Specification

The third optional field of the format specification is the precision specification. It specifies a nonnegative decimal integer, preceded by a period (.), which specifies the number of characters to be printed, the number of decimal places, or the number of significant digits. (See Table R.4.) Unlike the width specification, the precision specification can cause truncation of the output value, or rounding in the case of a floating-point value. If precision is specified as zero and the value to be converted is zero, the result is no characters output, as shown below:

printf( “%.0d”, 0 ); /* No characters output */

The precision specification may be an asterisk (*), in which case an int argument from the argument list supplies the value. The precision argument must precede the value being formatted in the argument list.

The interpretation of the precision value and the default when precision is omitted depend on the type, as shown in Table R.4.

Table R.4 How printf Precision Values Affect Type

Type Meaning Default

d i u o x X The precision specifies the minimum number of digits to be printed. If the number of digits in the argument is less than precision, the output value is padded on the left with zeros. The value is not truncated when the number of digits exceeds precision. , Default precision is 1.  
e E The precision specifies the number of digits to be printed after the decimal point. The last printed digit is rounded. Default precision is 6; if precision is 0 or the period (.) appears without a number following it, no decimal point is printed.
f The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits. Default precision is 6; if precision is 0, or if the period (.) appears without a number following it, no decimal point is printed.
g G The precision specifies the maximum number of significant digits printed. Six significant digits are printed, with any trailing zeros truncated.
c The precision has no effect. Character is printed.
s The precision specifies the maximum number of characters to be printed. Characters in excess of precision are not printed. Characters are printed until a null character is encountered.

If the argument corresponding to a floating-point specifier is infinite, indefinite, or not a number (NAN), the printf function gives the following output:

Value Output

+ infinity 1.#INFrandom-digits
– infinity –1.#INFrandom-digits
Indefinite digit.#INDrandom-digits
NAN digit.#NANrandom-digits

Size and Distance Specification

For printf, the format specification fields F and N refer to the “distance” to the object being read (near or far), and h and l refer to the “size” of the object being read (16-bit short or 32-bit long). The following list clarifies this use of F, N, h, l, and L:

Program Code Action

printf ("%Ns"); Print near string
printf ("%Fs"); Print far string
printf ("%Nn"); Store char count in near int
printf ("%Fn"); Store char count in far int
printf ("%hp"); Print a 16-bit pointer (xxxx)
printf ("%lp"); Print a 32-bit pointer (xxxx:xxxx)
printf ("%Nhn"); Store char count in near short int
printf ("%Nln"); Store char count in near long int
printf ("%Fhn"); Store char count in far short int
printf ("%Fln"); Store char count in far int

The specifications "%hs" and "%ls" are meaningless to printf. The specifications "%Np" and "%Fp" are aliases for "%hp" and "%lp" for the sake of compatibility with Microsoft C version 4.0.

Return Value

The printf function returns the number of characters printed, or a negative value in the case of an error.

Compatibility

Standards:ANSI, UNIX

16-Bit:DOS, QWIN

32-Bit:DOS32X

See Also

fprintf, scanf, sprintf, vfprintf, vprintf, vsprintf

Example

/* PRINTF.C illustrates output formatting with printf. */

#include <stdio.h>

void main( void )

{

char ch = 'h', *string = “computer”;

int count = -9234;

double fp = 251.7366;

/* Display integers. */

printf( “Integer formats:\n”

“\tDecimal: %d Justified: %.6d Unsigned: %u\n”,

count, count, count, count );

printf( “Decimal %d as:\n\tHex: %Xh C hex: 0x%x Octal: %o\n”,

count, count, count, count );

/* Display in different radixes. */

printf( “Digits 10 equal:\n\tHex: %i Octal: %i Decimal: %i\n”,

0x10, 010, 10 );

/* Display characters. */

printf( “Characters in field:\n%10c %5c\n”, ch, ch );

/* Display strings. */

printf( “Strings in field:\n%25s\n%25.4s\n”, string, string );

/* Display real numbers. */

printf( “Real numbers:\n\t%f %.2f %e %E\n”, fp, fp, fp, fp );

/* Display pointers. */

printf( “Address as:\n\tDefault: %p Near: %Np Far: %Fp\n”,

&count, (int __near *)&count, (int __far *)&count );

/* Count characters printed. */

printf( “Display to here:\n” );

printf( “1234567890123456%n78901234567890\n”, &count );

printf( “\tNumber displayed: %d\n\n”, count );

}

Output

Integer formats:

Decimal: -9234 Justified: -009234 Unsigned: 56302

Decimal -9234 as:

Hex: DBEEh C hex: 0xdbee Octal: 155756

Digits 10 equal:

Hex: 16 Octal: 8 Decimal: 10

Characters in field:

h h

Strings in field:

computer

comp

Real numbers:

251.736600 251.74 2.517366e+002 2.517366E+002

Address as:

Default: 141C Near: 141C Far: 0087:141C

Display to here:

123456789012345678901234567890

Number displayed: 16