Codiqo

Learn C · lesson 6 of 60 · about 8 minutes

Reading Input with scanf

Make the report personal: read the user's name and a backup size with scanf(), and see why it needs an address.

What you'll learn

  • Read an int with scanf
  • Read a double with %lf
  • Read a single word into a char array

scanf mirrors printf

scanf reads what the user types, using the same placeholders as printf: scanf("%d", &backup); reads a whole number into backup.

The & matters. scanf has to put the number in your variable's box, so you give it the box's address: &backup means "the address of backup".

Step through it to see where scanf writes

#include <stdio.h>

int main(void) {
    int used = 2560;
    int backup;
    scanf("%d", &backup);
    printf("After backup: %d KiB\n", used + backup);
    return 0;
}

Output

After backup: 3584 KiB

Other types

| To read | Use | Note |
|---|---|---|
| int | %d | needs & |
| double | %lf | l for "long float"; needs & |
| one word | %19s | into a char array; no & |

A word goes in a char array, a row of char boxes: char user[20];. The array's name is already the address of its first box, so it has no &. The 19 stops scanf writing more than the array holds, keeping one box for the marker that ends the text.

A word and a decimal

#include <stdio.h>

int main(void) {
    char user[20];
    double cpu;
    scanf("%19s", user);
    scanf("%lf", &cpu);
    printf("Report for %s, CPU at %.1f C\n", user, cpu);
    return 0;
}

Output

Report for ada, CPU at 47.5 C

Tip

%s stops at the first space. If the user types Ada Lovelace, user gets just Ada.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.