Print a Formatted Label
Match each value to its placeholder
You can now keep records alive long enough to use them. This section turns their values into messages and checks that text fits before accepting it; keyboard input comes last as optional local practice.
The event desk needs a sign for eight mending places. printf writes to stdout, the normal output stream. Its %s placeholder takes the activity string and %d takes the integer count, in that order. This program does not read stdin.
The first argument is the format string. The text around the placeholders is printed as written; each placeholder describes the next argument. A mismatched type is not automatically converted to whatever the placeholder asks for and can cause undefined behavior.
| Value supplied | printf placeholder | Example meaning |
|---|---|---|
int | %d | An integer count |
unsigned int | %u | An unsigned count |
size_t | %zu | A size or array length |
double | %f, or %.2f | Decimal output, optionally with two digits after the point |
| A null-terminated character string | %s | Text up to its terminator |
A character (promoted to int) | %c | One character |
Use %% for a literal percent sign. Keep the format string under your control: to print arbitrary text, use printf("%s", text), not printf(text). A percent sign in text should be data, not an instruction to read another argument.
#include <stdio.h>
int main(void) {
const char *activity = "Mending";
int places = 8;
printf("%s: %d places\n", activity, places);
return 0;
}
Run the example and match Mending to %s and 8 to %d. The final \n ends the line. The demonstration is a read-only block; in the following exercise you will write the call for a different sign.