C/C++ Arena

Step 2 of 5

Several values at once

One scanf call can read several values. List one format specifier per value, and one address per variable, in the same order:

#include <stdio.h>

int main(void) {
    int width, height;
    scanf("%d %d", &width, &height);
    printf("Area: %d\n", width * height);
    return 0;
}
12
5
Area: 60

Whitespace is flexible

When reading numbers, scanf skips any whitespace (spaces, tabs and newlines) before each one. So the program above reads the same values whether they're typed as 12 5 on one line or on two separate lines like in the example. A space in the format string also means "skip any amount of whitespace here", so "%d %d" and "%d%d" behave the same for numbers.

Other characters in the format string must match the input exactly. With "%d,%d" the input has to be 12,5; if a comma isn't there, reading stops early.

How scanf reads

Think of the input as a stream of characters with a reading position. Each %d skips whitespace, reads digits (and an optional sign) as far as they go, converts them to an int, and moves the position forward. The next scanf call continues from there. Reading is always left to right; nothing is read twice.

Your turn: read a player's kills and deaths and print their difference.

Input: 18 11 prints +/-: 7

Previous: Read a number Next: Reading doubles