C/C++ Arena

Step 5 of 5

Did the read work?

Input comes from people, and people type unexpected things. A robust program checks that each read actually worked.

scanf returns a number: how many values it successfully read and stored. With scanf("%d %d", &a, &b):

When a read fails, the variable keeps whatever it had before, which for an uninitialized variable is garbage. Using it anyway is a bug. So compare the return value with how many values you asked for:

#include <stdio.h>

int main(void) {
    int a, b;
    int got = scanf("%d %d", &a, &b);
    printf("read %d value(s)\n", got);
    if (got == 2) {
        printf("sum %d\n", a + b);
    }
    return 0;
}
7 seven
read 1 value(s)

if runs its block only when the condition in parentheses is true; you'll learn it properly in the next module. For now, the pattern if (scanf(...) == N) is all you need.

A failed read also leaves the bad characters in the input, so the next %d fails on them too. Real programs usually read a whole line and then parse it, which avoids that trap.

Your turn: read one int. If it worked, print Got N. Otherwise print Not a number.

Previous: Characters and words