← 返回课程: C programming from scratch

printf and format specifiers

视频即将上线

printf is the main way to show information in C. It receives a format string and then the values you want to insert. Inside the string, each mark that starts with % says where a value goes and what type it is. Understanding these specifiers well is essential, because printf does not check that the type you promise matches the value you pass: if you get it wrong, the result is garbage or a crash.

c
#include <stdio.h>

int main(void) {
    int age = 30;
    double height = 1.75;
    char initial = 'J';

    printf("Age: %d\n", age);
    printf("Height: %f meters\n", height);
    printf("Initial: %c\n", initial);
    printf("%d years and %.2f meters\n", age, height);
    return 0;
}

The most common specifiers

  • %d or %i: int (signed integer)
  • %u: unsigned int
  • %ld and %lld: long and long long
  • %f: double (it also works for float, which is promoted to double)
  • %c: a single character
  • %s: a string of text
  • %x: unsigned integer in hexadecimal
  • %zu: size_t, the type returned by sizeof and strlen
  • %p: a memory address (pointer)
  • %%: a literal % character

Width and precision

Between the % and the letter you can add modifiers. A number sets the minimum field width: %5d reserves five positions and aligns to the right. A minus sign aligns to the left: %-5d. A dot followed by a number controls the decimals in real numbers: %.2f shows two. A zero before the width pads with zeros: %04d shows 0042. With these pieces you can align tables easily.

c
#include <stdio.h>

int main(void) {
    printf("%-10s|%6s|\n", "Item", "Price");
    printf("%-10s|%6.2f|\n", "Coffee", 2.5);
    printf("%-10s|%6.2f|\n", "Sandwich", 4.75);
    printf("Order number: %04d\n", 42);
    printf("Discount: %d%%\n", 15);
    return 0;
}

This program prints a small table with aligned columns. Notice %% to show a real percent sign and %-10s to left-align text in ten positions.

Escape sequences

  • \n: line break
  • \t: tab
  • \\: a backslash
  • \": double quotes inside a string
  • \0: the null character, which marks the end of a string

A very common mistake is forgetting the final \n. The output of printf is usually kept in a buffer and, without a line break, the text may appear late or mixed with the terminal prompt. Another serious mistake is using the wrong specifier: printing a double with %d produces a meaningless value, and the compiler will only warn you if you use -Wall, because it checks literal format strings.

c
#include <stdio.h>

int main(void) {
    const char *text = "100%d is not a format here";
    printf("%s\n", text);   /* safe */
    /* printf(text);        UNSAFE: text is read as a format */
    printf("Tab:\tdone\n");
    printf("Quote: \"C\" and path C:\\temp\n");
    return 0;
}

Remember too that printf returns how many characters it printed, although it is almost never used. What matters is discipline: for each specifier there must be exactly one argument of the right type, in the same order. If you pass fewer arguments than needed, printf will read nonexistent values from the stack; if you pass more, it simply ignores them. Always check that correspondence before compiling.

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →