Page 127 - Programming Microcontrollers in C
P. 127
112 Chapter 2 Advanced C Topics
of several functions that can be grouped together under the category
of formatted input/output. The formatted output functions include
int printf(char* format, arg1, arg2,...);
int sprintf(char* string, char* format,
arg1,arg2,...);
int fprintf(FILE* fp, char* format, arg1,
arg2,...);
The function printf() has been used throughout the text so far,
and there should be little question as to its use. This function prints data
to the terminal screen. The pointer format points to a character string
that contains the information to print out. Within the format, there can
be conversion commands identified by a percent sign %. These com
mands will be discussed in detail later. The number or arguments, arg1,
arg2, etc. depend on the number of commands within the format string.
The second function above, sprintf(), performs exactly the
same conversion as printf(). Rather than printing the result to
the screen, it is written into the character array string in memory
designated by char* string.
Data can be printed to a file with the third function fprintf().
Here fp is the file pointer of an open file, and the remainder of the
arguments are exactly the same as with the printf() function.
The following is a list of all the conversion commands and their
meanings. If the character following the % in a format string is not
found in the table, function behaviors will be undefined.
Character Printed as
d,i int: decimal number
o int: unsigned octal number
x,X int: unsigned hexadecimal number
u int: unsigned decimal number
c int: single character
s char*: print characters from string until ‘\0’ is
detected.
f double: floating point [-]m.dddd where the num
ber of d’s is given by precision. Default precision is 6.
e,E double:floating point [-]m.ddddExx where the num
ber of d’s is given by the precision, and the power of 10
exponent can be plus or minus. Default precision is 6.