02. Formatted Input with scanf & Return Validation

🟢 Difficulty: Beginner | Keyboard Input Parsing, Memory Addresses & Validation

📖 Definition

The scanf() function reads formatted input from the standard input stream (stdin), parses the sequence of text characters typed by the user according to specified format specifiers, and stores the converted binary values into memory locations supplied by address-of pointers (&variable).

🎯 Why It Is Used

  • Interactive Data Acquisition: Allows applications to accept integers, floats, characters, and tokens from keyboard input.
  • Input Validation via Return Value: scanf() returns the number of input items successfully matched and assigned. Checking this return value prevents reading uninitialized garbage variables when users type invalid data.

⚙️ How It Works: Memory Pointers & Stream Matching

Because C passes parameters by value, passing a variable directly to scanf() (e.g. scanf("%d", num)) fails because scanf() receives a copy of num's value. To mutate num, you must pass its memory address using the address-of operator &num (e.g. scanf("%d", &num)).

📝 Syntax

// Reading primitive data types require & address operator
int val;
int items_scanned = scanf("%d", &val);

// Arrays (like char arrays) decay to pointers, so & is omitted
char code[20];
scanf("%19s", code); // Width limit 19 prevents buffer overflow!

🔀 Unbounded vs Field-Bounded Specifiers

Pattern Safety Level Risk Assessment
scanf("%s", buffer); 🔴 Highly Unsafe Does NOT check buffer limits. Typing a word longer than buffer overwrites RAM (Buffer Overflow Vulnerability).
scanf("%39s", buffer); 🟢 Safe Token Read Limits reading to 39 characters max plus \0 null terminator. Stops at whitespace.
if (scanf("%d", &val) == 1) 🟢 Validated Primitive Read Checks if user typed a valid integer before processing.

🌱 Beginner Example: Simple Integer Read

#include <stdio.h>

int main(void) {
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);

    printf("You entered: %d years old.\n", age);
    return 0;
}

🌼 Intermediate Example: Input Validation with Return Value Checking

#include <stdio.h>

int main(void) {
    int quantity;
    double price;

    printf("Enter quantity and unit price (e.g. 5 19.99): ");
    int matched = scanf("%d %lf", &quantity, &price);

    if (matched != 2) {
        printf("Error: Invalid input format! Expected integer and double.\n");
        return 1;
    }

    printf("Total Cost: $%.2lf\n", quantity * price);
    return 0;
}

🌲 Advanced Example: Handling Input Failure & Clearing Buffer

#include <stdio.h>

void clear_stdin_buffer(void) {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

int main(void) {
    int target_number;

    while (1) {
        printf("Enter a positive integer target (1-100): ");
        if (scanf("%d", &target_number) == 1 && target_number >= 1 && target_number <= 100) {
            break; // Valid input received
        }
        printf("Invalid input! Please enter a valid number between 1 and 100.\n");
        clear_stdin_buffer(); // Clear invalid non-numeric text from stream
    }

    printf("Target set to: %d\n", target_number);
    return 0;
}

🔍 Line-by-Line Explanation

  • int matched = scanf("%d %lf", &quantity, &price);: Scans 2 variables and returns total successfully converted items.
  • if (matched != 2): Verifies that both quantity and price were parsed cleanly. If a user types "abc 12", matched will be 0 and the error block executes.
  • while ((c = getchar()) != '\n' && c != EOF);: Discards invalid non-numeric text left behind in the stdin buffer.

💻 Expected Terminal Output

Enter a positive integer target (1-100): abc
Invalid input! Please enter a valid number between 1 and 100.
Enter a positive integer target (1-100): 42
Target set to: 42

⚠️ Common Mistakes & Pitfalls

  • Forgetting & Operator: Writing scanf("%d", val) passes the uninitialized value of val as a pointer address, causing Segmentation Fault crash.
  • Unbounded scanf("%s"): Using %s without field width limits causes severe buffer overflow security vulnerabilities.
  • Ignoring Return Values: Assuming scanf() succeeded without checking its return value leads to processing uninitialized garbage values.

📌 Important Rules & Limitations

  • scanf("%s") stops reading at whitespace (spaces, tabs, newlines). For multi-word string inputs containing spaces, use fgets().
  • Format specifier for double in scanf() must be %lf (unlike printf() where %f handles both).

🌐 Multilingual Explanation: English

scanf() parses input from standard input and requires address-of pointers (&var) for non-array variables. Always check scanf()'s return value to verify that user input was successfully parsed before using variables.

🌐 Multilingual Explanation: Hindi (Roman Script)

scanf() keyboard se input read karta hai aur ise variable ka address (&var) chahiye hota hai. Input sahi hai ya nahi ye check karne ke liye scanf() ke return value ko if (scanf(...) == 1) se hamesha check karein.

🌐 Multilingual Explanation: Marathi (Roman Script)

scanf() vapartana variables cha address (&var) dyava lagto. User ne dilela input barobar vachla gela aahe ki nahi he pahnaysathi scanf() chi return value check karni avashyak aahe.

❓ Practice Questions

  1. Why is the & operator required for int variables in scanf() but not for character array strings?
  2. What does scanf() return if user input fails to match the expected format?
  3. How does field width specification (e.g. %19s) prevent buffer overflow attacks?

🚀 Practical Coding Challenge

Write a program named safe_calculator.c that prompts the user for two integers and an operator char (+, -, *, /). Validate all inputs using scanf() return value checking, handle division by zero safely, and print the calculated result.

🧭 Navigation & Breadcrumbs

← Previous: 01. Formatted Output with printf | Module 04 Guide | Next: 03. Character Streams (getchar, putchar) →