Handling Input Errors in C

The scanf() function returns the number of inputs successfully read. You can use this to check whether the user gave valid input.


πŸ›  Example: Check for a Valid Integer

#include <stdio.h>

int main() {
    int age;
    int result;

    printf("Enter your age: ");
    result = scanf("%d", &age);   // Try to read an integer

    if (result == 1) {
        printf("You are %d years old.\n", age);
    } else {
        printf("Invalid input! Please enter a number.\n");
    }

    return 0;
}

πŸ” What’s Happening:

StepExplanation
scanf("%d", &age)Reads the user input.
result = scanf(...)Stores how many items were successfully read.
if (result == 1)If the user entered a valid integer, scanf returns 1.
ElseIf the input fails (e.g., user types letters), it returns 0.

πŸ›  Example: Handle String and Number Together

#include <stdio.h>

int main() {
    char name[50];
    int age;
    int result;

    printf("Enter your name and age (e.g., John 25): ");
    result = scanf("%s %d", name, &age);

    if (result == 2) {
        printf("Hello, %s! You are %d years old.\n", name, age);
    } else {
        printf("Invalid input! Please enter your name followed by a number.\n");
    }

    return 0;
}

βœ… Why This Matters

In C:

  • If the user types something unexpected (like a word when a number is expected), your program might behave unpredictably if you don’t check.
  • Using scanf()’s return value is a simple way to validate input.

πŸ”„ Limitations & Next Steps

βœ”οΈ This method detects basic errors, like wrong types.
⚠️ But C doesn’t automatically clear the input buffer (e.g., if the user types abc when a number is expected, it might leave garbage in memory).

For more robust input handling, you can:

  • Use fgets() to read a whole line.
  • Then parse it with functions like sscanf(), atoi(), or strtol(), giving you more control and safety.

πŸ”š Conclusion

  • βœ… Always check the return value of scanf() for safe input.
  • βœ… For simple programs, this is usually enough.
  • πŸš€ As your programs grow, consider using fgets + sscanf for better safety.
Feedback Display

Learner Reviews