Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 15 min

Reading the keyboard with scanf

By the end of this chapter, you'll be able to

  • Read a whole number and a decimal number with scanf
  • Explain why scanf needs & in front of the variable name
  • Check the value returned by scanf to detect invalid input
  • Test a program that reads the keyboard

Reading a number

scanf ("scan formatted") is the opposite of printf: it reads the keyboard and stores what it finds in your variables, following a format.

#include <stdio.h>

int main(void) {
    int age = 0;
    printf("How old are you? ");
    if (scanf("%d", &age) != 1) {
        printf("That's not a whole number.\n");
        return 1;
    }
    printf("In 10 years, you'll be %d.\n", age + 10);
    return 0;
}

If the user types 17 then Enter:

17
How old are you? In 10 years, you'll be 27.

(In a real terminal, the 17 you type appears after the question, and the result shows up on the next line.)

Three important details:

  • the format follows the same rules as printf, except for doubles, which are read with %lf ("long float");
  • the & in front of age gives scanf the address of the variable, that is, the place in memory where it lives. scanf needs to know where to write. We'll look at addresses in detail with pointers;
  • scanf returns the number of values it managed to read. If the user types hello instead of a number, it returns 0, and age isn't changed. Checking this result protects your program against invalid input.

The return 1; ends the program with an error code: a well-behaved program reports its failures.

scanf returns 0 and age keeps its value. Without a check, the program would carry on with a wrong value.

Step 6 of 6
Text description of the animation
  1. The user types the characters 1 and 7, then Enter. For now, it's just text.
  2. scanf reads these characters and converts them into the integer 17, as %d requires.
  3. Thanks to the address &age, scanf stores 17 directly in the box age.
  4. scanf returns 1: one value was read. The program can carry on.
  5. If the user types "hello", the conversion fails from the very first letter.
  6. scanf returns 0 and age keeps its value. Without a check, the program would carry on with a wrong value.

Reading several values

A single scanf can read several values, separated by spaces or line breaks:

#include <stdio.h>

int main(void) {
    double price = 0;
    int quantity = 0;
    if (scanf("%lf %d", &price, &quantity) != 2) {
        printf("Invalid input.\n");
        return 1;
    }
    printf("Total: %.2f\n", price * quantity);
    return 0;
}
2.5 4
Total: 10.00

Your turn

Worked exercise

Worked exercise: odd or even?

Write a program that asks for an integer, checks that the input is valid, then displays whether it's odd or even. With the input -7, it must display -7 is odd.

Hint 1
A number is even if the remainder of its division by 2 is 0: n % 2 == 0.
Hint 2
Watch out for negative numbers: in C, -7 % 2 is -1, not 1. So test n % 2 == 0 rather than n % 2 == 1.
Show the solution and common mistakes
#include <stdio.h>

int main(void) {
    int n = 0;
    printf("Enter an integer: ");
    if (scanf("%d", &n) != 1) {
        printf("\nThat's not an integer.\n");
        return 1;
    }
    if (n % 2 == 0) {
        printf("%d is even\n", n);
    } else {
        printf("%d is odd\n", n);
    }
    return 0;
}
-7
Enter an integer: -7 is odd

Common mistakes:

  • Testing n % 2 == 1: it's wrong for negative numbers, because the remainder is then -1.
  • Not checking the value returned by scanf: with the input abc, the program would claim that 0 is even.

Summary

  1. 1scanf reads the keyboard following a format: %d for int, %lf for double.
  2. 2You must give it the address of the variable with & (for example &age).
  3. 3scanf returns the number of values read: always check it.
  4. 4On invalid input, display a message and end with return 1.
  5. 5-Wall catches a forgotten & or a format that doesn't match the type.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.