Skip to content
CurriculumChapter 04 ยท Foundations
BeginnerHigh focus~14 min

printf, scanf & Formatted I/O

printf writes formatted text, scanf reads formatted input. The format string is a contract: get it wrong and the program misreads memory.

In plain English

printf is your mouth and scanf is your ears. The format string tells both what kind of thing to expect.

01

printf and format specifiers

printf writes to standard output. Common specifiers are %d for int, %f for double, %c for char, %s for a string, %u for unsigned, and %p for a pointer. Width, precision, and flags control padding and rounding, for example %05d or %.2f. The return value is the number of characters written, or a negative value on error.

chapter-04.cC
int age = 21;
double price = 19.5;
printf("age=%d price=%.2f\n", age, price);
printf("padded=%05d\n", 42);   /* 00042 */
02

scanf, addresses, and validation

scanf reads formatted input. Pass the address of the variable, not the variable itself: scanf("%d", &age). It returns the number of items successfully assigned, which lets you detect bad input. A string read with %s stops at whitespace and can overflow the destination, so limit the width or use fgets instead.

chapter-04.cC
int age;
if (scanf("%d", &age) != 1) {
    fprintf(stderr, "not a number\n");
    return 1;
}
printf("next year: %d\n", age + 1);

Key takeaways

  • printf uses format specifiers; scanf needs the address of the destination.
  • Check scanf return values to detect failed conversions.
  • %s in scanf stops at whitespace and can overflow.
  • Width and precision control output formatting.

Common pitfalls

  • Passing a value instead of an address to scanf.
  • Leaving a newline in the input buffer after scanf.
  • Using %s without a field width on untrusted input.

Key focus

  • Predict output with width and precision flags.
  • Know the return values of printf and scanf.

Quick check

0 / 2 answered

1. Which call correctly reads an int into variable n?

2. What does printf return?