Formatted Input & Output

Formatted Input & Output in C: is not a print statement. It is a form with blanks in it, and you supply the values that go in the blanks.

The Analogy: A Fill-in-the-Blanks Form

printf is not a print statement. It is a form with blanks in it, and you supply the values that go in the blanks.

"Dear ____, your balance is $____ as of ____." Hand that form to printf along with a name, a number, and a date, and it fills the blanks in order. The blanks are the % specifiers, and each one declares what kind of thing belongs there — a whole number, a decimal, a character, a string.

The catch is that the form does not check your answers. If a blank says "put a whole number here" and you hand it a decimal, printf will read four bytes out of an eight-byte value and print whatever that happens to mean. scanf is the same form running backwards, and it is even less forgiving, because it writes into your memory rather than reading from it.


Syntax or Core Structure

#include <stdio.h>

int main(void) {
    int    quantity = 3;
    double price    = 4.5;
    char   initial  = 'R';
    char   city[]   = "Lisbon";

    printf("Quantity: %d\n", quantity);
    printf("Price:    %.2f\n", price);
    printf("Initial:  %c\n", initial);
    printf("City:     %s\n", city);
    printf("Total:    %d items at %.2f = %.2f\n",
           quantity, price, quantity * price);
    return 0;
}

Output:

Quantity: 3
Price:    4.50
Initial:  R
City:     Lisbon
Total:    3 items at 4.50 = 13.50

The arguments are consumed strictly left to right, one per specifier. Supply too few and printf reads whatever garbage is next in the argument registers; supply too many and the extras are silently ignored.

The specifiers you will actually use

SpecifierReads / printsExample output
%dint in decimal-42
%uunsigned int4294967295
%ld / %lldlong / long long9000000000
%fdouble (and float, promoted)3.140000
%.2fdouble, two decimals3.14
%escientific notation3.14e+00
%csingle charA
%sstring, up to the \0Lisbon
%x / %ohexadecimal / octalff / 377
%pa pointer's address0x7ffd3c1a
%zusize_t, as from sizeof8
%%a literal percent sign%

Width, precision, and alignment

#include <stdio.h>

int main(void) {
    printf("[%5d]\n",    42);       // width 5, right aligned
    printf("[%-5d]\n",   42);       // width 5, left aligned
    printf("[%05d]\n",   42);       // pad with zeros
    printf("[%8.3f]\n",  3.14159);  // width 8, 3 decimals
    printf("[%-10s|]\n", "hi");     // strings pad too
    printf("[%+d] [%+d]\n", 42, -42);
    return 0;
}

Output:

[   42]
[42   ]
[00042]
[   3.142]
[hi        |]
[+42] [-42]

The general shape is %[flags][width][.precision]specifier. This is how you get columns to line up in a report without doing any arithmetic yourself.


Technical Depth: Why scanf Is Dangerous

scanf writes into memory you name. That means every call is a chance to write somewhere you did not intend.

#include <stdio.h>

int main(void) {
    int age = 0;

    printf("Age: ");
    if (scanf("%d", &age) != 1) {         /* note the & */
        printf("That was not a number.\n");
        return 1;
    }
    printf("You are %d\n", age);
    return 0;
}

Three things in that tiny program are load-bearing:

  • The &. scanf needs the address of age so it can store into it. Writing scanf("%d", age) passes the current value of age — likely 0 — and scanf treats it as an address and writes there. That is an immediate segmentation fault on a good day and silent corruption on a bad one.
  • The return value. scanf returns the number of items it successfully converted, or EOF. If the user types "banana", it converts nothing, returns 0, and leaves age untouched.
  • No & for arrays. scanf("%s", name) is correct with char name[50], because an array name already decays to the address of its first element.

The leftover newline problem

#include <stdio.h>

int main(void) {
    int  count = 0;
    char code  = 0;

    printf("Count: ");
    scanf("%d", &count);

    printf("Code letter: ");
    scanf(" %c", &code);        /* the leading space is essential */

    printf("count=%d code=%c\n", count, code);
    return 0;
}

When you type 5 and press Enter, %d consumes the 5 and leaves the \n sitting in the input buffer. The next %c would happily read that newline as your "code letter". The leading space in " %c" tells scanf to skip any amount of whitespace first. %d, %f, and %s skip leading whitespace automatically; %c is the exception.

Bounding string input

char name[50];
scanf("%s", name);      /* DANGEROUS: no limit, will overflow past 50 */
scanf("%49s", name);    /* safe: at most 49 chars plus the '\0' */

Unbounded %s is the classic buffer overflow. The width must be one less than the array size, because scanf adds the terminating zero itself.

When you want a whole line

#include <stdio.h>
#include <string.h>

int main(void) {
    char line[100];

    printf("Full name: ");
    if (fgets(line, sizeof line, stdin) == NULL) {
        return 1;
    }
    line[strcspn(line, "\n")] = '\0';   /* trim the trailing newline */

    printf("Hello, [%s]\n", line);
    return 0;
}

Output:

Full name: Grace Hopper
Hello, [Grace Hopper]

scanf("%s") stops at the first space, so it can never read "Grace Hopper" as one value. fgets reads the whole line, bounded by the buffer size, and keeps the newline — which is why the strcspn line trims it. For interactive input, fgets plus parsing is almost always the better choice.

scanf versus fgets

scanffgets
Readsone token at a timeone whole line
Stops atwhitespacenewline or buffer full
Boundsonly if you write the widthalways, via the size argument
Leaves newline in bufferyesno, it consumes it
Handles "Grace Hopper"no, stops at the spaceyes
Failure signalcount of items convertedNULL

Real World Example: An Invoice Line Printer

#include <stdio.h>
#include <string.h>

int main(void) {
    char   item[40];
    int    quantity   = 0;
    double unit_price = 0.0;

    printf("Item description: ");
    if (fgets(item, sizeof item, stdin) == NULL) return 1;
    item[strcspn(item, "\n")] = '\0';

    printf("Quantity: ");
    if (scanf("%d", &quantity) != 1) {
        printf("Quantity must be a whole number.\n");
        return 1;
    }

    printf("Unit price: ");
    if (scanf("%lf", &unit_price) != 1) {      /* %lf for double in scanf */
        printf("Price must be a number.\n");
        return 1;
    }

    double subtotal = quantity * unit_price;
    double tax      = subtotal * 0.20;

    printf("\n%-20s %5s %10s %10s\n", "ITEM", "QTY", "UNIT", "AMOUNT");
    printf("%-20s %5d %10.2f %10.2f\n", item, quantity, unit_price, subtotal);
    printf("%-20s %5s %10s %10.2f\n", "VAT at 20%", "", "", tax);
    printf("%-20s %5s %10s %10.2f\n", "TOTAL", "", "", subtotal + tax);
    return 0;
}

Output:

Item description: USB-C cable, 2m
Quantity: 3
Unit price: 8.50

ITEM                   QTY       UNIT     AMOUNT
USB-C cable, 2m          3       8.50      25.50
VAT at 20%                                  5.10
TOTAL                                      30.60

The column alignment is done entirely with width specifiers, which is why the numbers line up without a single space being counted by hand. %-20s left-aligns the description in a twenty-character field; %10.2f right-aligns money in a ten-character field with two decimals. Note %lf in scanf versus %f in printf for the same double: printf promotes float to double automatically so both work, but scanf receives an address and must be told the exact width, so %f there would write only four bytes and corrupt the variable.


Common Mistakes

  1. Forgetting the & on a numeric scanf. The most common crash in beginner C.
  2. Adding an & to an array: scanf("%s", &name) where name is char[50]. It usually works by accident, and it is wrong.
  3. Unbounded %s, allowing input longer than the array.
  4. Using %f in scanf for a double. It must be %lf, or you write four bytes into eight and corrupt neighbours.
  5. Reading a char with %c right after %d and getting the leftover newline instead of the character.
  6. Ignoring scanf's return value, then computing with a variable that was never assigned.
  7. Mixing scanf and fgets without clearing the buffer, so fgets immediately returns an empty line.
  8. Writing %s for a single char. printf("%s", 'A') treats the value 65 as an address and crashes.
  9. Assuming output appears immediately. Standard output to a terminal is line-buffered, so a prompt without \n may not show until something flushes it.

Best Practices

  • Use fgets plus sscanf or strtol for interactive input; keep bare scanf for exercises and throwaway tools.
  • Always check the return value of scanf and fgets.
  • Always give %s a width, one less than the array size.
  • Write sizeof buffer rather than repeating the literal size, so the two can never drift apart.
  • Put a leading space before %c unless you specifically want the whitespace.
  • Use width and precision specifiers to align tables rather than padding with spaces by hand.
  • Print prompts without \n only if you also fflush(stdout); otherwise end them with a newline.
  • Compile with -Wall, which checks printf and scanf format strings against the arguments you passed.

Practice Exercises

  1. Break It On Purpose: Write a program that reads an int with scanf but omit the &. Compile with -Wall, read the warning, run it, then fix it and describe what happened.
  2. The Newline Hunt: Read an int and then a char using "%c" with no leading space. Show that the character is the newline, then fix it with " %c".
  3. Receipt Formatter: Read three item names and prices with fgets and sscanf, then print them as a right-aligned table with a total row, using only width specifiers for alignment.
  4. Safe by Construction: Write a program with a char buf[8] that reads a word with a bounded %s, then prove with a long input that nothing beyond the buffer is written and the string is still terminated.