Input and output routines are provided in the C language. To access the functions for using formatted input and output, the following compiler control line must be included at the beginning of the source file:
#include <stdio.h>
This include file contains the header information for STandarD Input/Output functions. This documentation only explains the basics; check the fprintf man page for further information.
printf() prints output to standard output, the text screen being the default. Its syntax is as follows:
printf(control_string, arg1, arg2, ...)
The control string is a double-quoted text string which contains conversion and formatting information about how the remaining arguments are to be handled. An example call would take the form:
printf("A height of %d and a base of %.1f would ...", h, b)
and would generate the following output if h and b had the values 5 and 7.5, respectively.
A height of 5 and a base of 7.5 would ...
Between the % and the conversion character (d in the case above), it is possible to include various formatting information, in the following order. All of these are optional.
| - | A minus sign to specify that the resulting text should be quadded to the left. |
| mm | A numeric value to specify the minimum field width. The converted number will be printed in a field that is at least this wide; if the field is larger than needed, it will be padded with blanks. |
| . | A period to separate the field width from the precision width. |
| nn | A numeric value to specify the number of digits to be printed to the right of the decimal point for a float or double (its precision), or the maximum number of characters to be printed from a string. |
| d | The argument is converted to decimal notation. |
| o | The argument is converted to unsigned octal notation (without a leading zero). |
| x | The argument is converted to unsigned hexadecimal notation (without a leading 0x). |
| u | The argument is converted to unsigned decimal notation. |
| c | The argument is taken to be a single character. |
| s | The argument is a string; characters from the string are printed until a null character is reached or the number of characters indicated by the precision specification is exhausted. |
| f | The argument is assumed to be a float or double and converted to decimal notation of the form [-]mmm.nnnnn where the length of the string of n's is specified by the precision (the default is 6). |
Strings are handled somewhat differently. The precision numeric indicates how many of characters starting from the beginning of a string will be printed. The following examples show the results when using various format specifications for the string "hello, world", which consists of 12 characters. A colon marks the end of the field.
Output Format
hello, world: %s or %10s or %-10s
hello, world: %20s
hello, world : %-20s
hello, wor: %20.10s
hello, wor : %-20.10s
hello, wor: %.10s