CodeBlanks Logo Icon CodeBlanks

scanf

Learn to read input from the user with scanf.

Reading input with scanf

The scanf function reads input from the keyboard. The format specifier tells the type to read; the second argument must be the address of the variable. The & sign gives the address.

int age;
printf("Age: ");
scanf("%d", &age);
printf("Hello, you are %d!\n", age);

The screen first shows Age: , the user types a number and presses Enter. scanf writes this value to the memory address of age. Forgetting & is a common mistake; the program may crash.

The scanf return value

scanf returns the number of items successfully read. If the user types a letter instead of a number, the read fails and the return value is 0. So checking the input is a good habit.

int n;
int result = scanf("%d", &n);
if (result == 1) {
    printf("Read: %d\n", n);
} else {
    printf("Invalid input!\n");
}

You'll see the if statement in detail in the next section; for now it's enough to know that checking the scanf return value is possible.

Practice Read an age input and print it

Write a C program. Declare int age;. Print a request line with printf, read the input with scanf("%d", &age);, then print the result with printf using the %d specifier. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare age, read input and print it
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int age;
    printf("Age: ");
    scanf("%d", &age);
    printf("Your age: %d\n", age);
    return 0;
}

Expected output

Age: Your age: 25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add the address operator

Question
scanf("%d", ____age);
Answer
scanf("%d", &age);

Explanation: & gives the address of age.

2 What does scanf("%d", &n) do?

main.c
int n;
scanf("%d", &n);
  • Prints the address of n
  • Prints an integer to the screen
  • Resets n to zero
  • Reads an integer from the keyboard Correct answer

Explanation: scanf reads an integer from the keyboard into n.

3 Match the scanf pieces

Term Meaning
%d Reads an integer
&age Gives the address
scanf Input function
printf Output function

All lessons in Beginner