Using printf() and sprinf() in C

We will extensively use the standard C functions printf() and sprintf(). In C usage of both function requires to include the <stdio.h> header. Check the Linux manual for these functions: man printf for more details.

Formatted output with printf()

The standard library function printf() is used for formatted output. It takes as arguments a format string and an optional list of variables or literals to output. The variables and literals are output according to the specifications in the format string. Here is the prototype for printf():

int printf(const char *format, arg_1, arg_2, arg_3, ... , arg_n);

The format string may consists both of character literals, and determines how printf() will format arg_1 - arg_n. Each of the arguments arg_1 - arg_n requires a format specifier, begins with the character % and has the following syntax:

%[-][+][0][x[.y]]conv

Here the terms put in brackets are optional. The meaning of these terms is as follows:

term meaning
- left justify the argument
+ print a number with its sign, + or -
0 pads a number with leading zeros
x minimum field width
.y number of decimal places

The conv is a character from the following list:

conv meaning
d integer
e exponential notation
f floating point number
c a character
o unsigned octal
s string of characters
x unsigned hexadecimal

Strings must be passed to printf() by reference, numbers and single characters - by value.

Composing strings with sprintf()

The sprintf() function prototype is

int sprintf(char *str, const char *format, arg_1, arg_2, arg_3, ... , arg_n);

This function works like printf() with the only difference is that the composed string is not output to the standard output, but is placed in array of characters passed as the first parameter. The other parameters have the same meaning and syntax as for printf(). The composed string is 0-terminated, so you must allocate enough space to store it.

Example:

char str[20];
int hours = 16;
sprintf(str, "%d:%02d", hours, 5);

The above code composes the following zero-terminated string: str="16:05".