Course contentsShow
← C
Lesson 696 of 1,21910. Input and OutputFree lesson

Handling the return value of scanf

Handling the return value of scanf

What you'll learn: How to use scanf's secret "receipt" to verify that your program actually received the data it expected.

The Receipt Analogy

Imagine you are at a fast-food drive-thru. You order a burger and a soda. In a perfect world, the employee hands you two items, you pay, and you drive away. But what if they only hand you the burger? If you don't check your bag before leaving, you'll get home and realize your meal is incomplete.

In C, scanf works exactly like that drive-thru. When you ask it to grab data, it doesn't just perform the action; it hands you a "receipt" in the form of an integer. This integer tells you exactly how many items it successfully picked up and stored in your variables.

Checking the Count

Most beginners assume scanf always works, but if a user types "hello" when your code expects a number, scanf fails silently. The variables won't be updated, and your program might behave unpredictably.

To stay safe, you should store the result of scanf in a variable and check it. If you asked for two numbers, the return value should be 2. If it's anything less, something went wrong.

Seeing it in Action

Here is how you can use the return value to catch input errors:

#include <stdio.h>

int main() {
    int age;
    float weight;
    int itemsRead;

    printf("Enter your age and weight: ");
    
    // scanf returns the number of items successfully filled
    itemsRead = scanf("%d %f", &age, &weight);

    if (itemsRead == 2) {
        printf("Success! Age: %d, Weight: %.1f\n", age, weight);
    } else {
        printf("Error: Invalid input. I only found %d of the 2 items requested.\n", itemsRead);
    }

    return 0;
}

Why This Matters

If the user types "25 150.5", itemsRead will be 2. However, if they type "25 pizza", scanf will successfully read the 25, but it will choke on "pizza" because it isn't a float. It will return 1, leaving the weight variable untouched. By checking this return value, you prevent your program from processing "garbage" data and crashing later on.

Key takeaway

Always check that scanf returns the exact number of items you expected to read before trusting the data.