Skip to content

Beginner · Getting started with C · topic 5 of 60 · 30 min

Input and output: printf and scanf

Explanation

printf prints formatted output using specifiers such as %d, %f, %c, %s, %x and %p, with optional width and precision (%8.2f). scanf reads input into variables and needs their addresses (&n). Always check scanf's return value, read lines safely with fgets, and never use %s without a width limit.

printf: formatted output

c
int qty = 3;
double price = 249.5;
char grade = 'A';
const char *city = "Pune";

printf("%d items at Rs %.2f each\n", qty, price);   // 3 items at Rs 249.50 each
printf("Grade %c, city %s\n", grade, city);         // Grade A, city Pune
printf("[%5d] [%-6s] [%08.3f]\n", 42, "ok", 3.14159); // [   42] [ok    ] [0003.142]
printf("%x %X %o\n", 255, 255, 8);                   // ff FF 10
printf("100%% done\n");                               // %% prints a percent sign
SpecifierTypeExample
%d or %iint42
%uunsigned int42
%ld / %lldlong / long long9000000000
%f / %.2fdouble (and float, promoted)3.14
%edouble in scientific notation3.140000e+00
%ccharA
%sstring (char *)Pune
%x / %ounsigned int in hex / octalff / 17
%ppointer, passed as (void *)0x7ffd…
%zusize_t8
%%a literal %%
Careful: A specifier that does not match its argument is undefined behaviour: printf("%d", 3.5) prints garbage, and printf("%s", 65) usually crashes. Compile with -Wall; gcc checks printf formats and warns about these mismatches.

Escape sequences

Inside string and character literals, a backslash starts an escape: \n new line, \t tab, \\ a backslash, \" a double quote, \' a single quote, and \0 the null character (used to end strings, module 4).

scanf: reading input

c
int age;
double height;
printf("Age and height: ");
int got = scanf("%d %lf", &age, &height);   // & gives the ADDRESS where scanf stores the value
if (got != 2) {
    printf("Please enter a number and a decimal.\n");
    return 1;
}
printf("Age %d, height %.2f\n", age, height);
Note %lf for double in scanf (but %f for double in printf).

scanf needs the address of each variable (written &variable) so it can store the value there; you will understand why with pointers in module 5. It returns how many values it successfully read (or EOF at end of input). Checking that number is the only way to know the input was valid.

Common scanf traps

  • Forgetting &: scanf("%d", age) passes a garbage address and usually crashes.
  • The leftover newline: after scanf("%d", &n), the Enter key stays in the input, so a following scanf("%c", &ch) reads that newline. Write " %c" (with a space) to skip whitespace first.
  • Unbounded strings: scanf("%s", name) can write past the end of the array (a buffer overflow). Always give a width one less than the array size: char name[20]; scanf("%19s", name);
  • %s stops at the first space, so "Ravi Kumar" reads only "Ravi".

Reading a whole line: fgets

c
char line[100];
if (fgets(line, sizeof line, stdin) != NULL) {   // reads at most 99 chars + '\0', including the newline
    line[strcspn(line, "\n")] = '\0';            // remove the newline (needs <string.h>)
    printf("You typed: %s\n", line);
}
fgets never writes past the array; module 4 covers it fully.
Think of it like this: A printf format string is like a printed form with blanks: "Name: ___ Age: ___". Each specifier is a blank of a particular kind, and the arguments fill the blanks in order. Put a number in a name blank, and the form comes out wrong.
Tip: For programs that read numbers from users, a robust pattern is: read a whole line with fgets, then convert it with strtol or sscanf, and check the result. Module 4 shows strtol.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Input and output: printf and scanf · 1/6

printf and scanf

In this lesson you will print formatted output and read input from the keyboard.

Prefer a video by a teacher? Find free videos on “c printf scanf format specifiers tutorial fgets” on YouTube ↗

In real life: A bill printer at a canteen counter

A college canteen's counter program reads an item code and quantity, checks that both were read, and prints a neatly aligned bill line using width and precision specifiers.

c
#include <stdio.h>

int main(void) {
    int code, qty;
    printf("Item code and quantity: ");
    if (scanf("%d %d", &code, &qty) != 2 || qty <= 0) {
        printf("Invalid input\n");
        return 1;
    }
    double price = (code == 1) ? 15.0 : 40.0;   /* 1 = tea, anything else = snack */
    printf("%-8s x%-3d Rs %7.2f\n", code == 1 ? "Tea" : "Snack", qty, qty * price);
    return 0;
}
Input 1 4 prints: Tea x4 Rs 60.00

Practice (0/3 done)

Task 1 · Question

What does printf("[%6.2f]", 3.14159); print?

Task 2 · Question

Which line has the bug? 1: int n; 2: printf("Enter n: "); 3: scanf("%d", n); 4: printf("%d\n", n * 2);

Task 3 · Practice

Write marks.c that reads a student's name (one word, at most 29 characters) and three integer marks with scanf, checks that scanf returned the right count, and prints a report: the name left-aligned in 15 characters, the total, and the average with 2 decimals.

Quick quiz

Question 1

1.Which scanf format reads a double?

Question 2

2.What does scanf return?

Question 3

3.char name[10]; Which is safe?

Question 4

4.How do you print a literal percent sign with printf?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which scanf format reads a double?

Answer: %lf

scanf needs %lf for double (printf accepts %f).

What does scanf return?

Answer: The number of items successfully read (or EOF)

Check it against the expected count.

char name[10]; Which is safe?

Answer: scanf("%9s", name)

Leave one byte for the terminating \0.

How do you print a literal percent sign with printf?

Answer: %%

%% prints %.

fgets returns NULL when…Related

Answer: End of input is reached (or an error occurs) before reading anything

Check it before using the buffer.

From Reading strings safely

Why does scanf("%d", &n) need &n?Related

Answer: So scanf can write the value into n through its address

scanf writes through the pointer.

From Pointers and functions

How do you print a literal % sign with printf?Related

Answer: %%

%% prints one percent sign.

From StringBuilder and formatting

How many bytes does "UPI" occupy as a string literal?Related

Answer: 4

3 letters + the terminator.

From Strings are char arrays

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Getting started with C”. The module exam comes next.
  2. Module 1 exam: Getting started with C · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Operators and control flow. 60 topics left in the course before the final exam.

← Previous: Data types and their sizes