-
Hajipur, Bihar, 844101
Input validation in C ensures that the data entered by a user or received from another source is correct, complete, and safe. Without proper validation, programs may produce incorrect results, crash, or even expose security vulnerabilities. This tutorial explains input validation techniques, common errors, best practices, and practical examples in C programming.
Input validation is the process of verifying that user input meets the program's requirements before processing it. For instance:
Numbers must fall within a specified range.
Characters must be among allowed options.
Strings must not exceed the allocated buffer size.
Proper validation prevents errors, enhances program reliability, and improves user experience.
Prevents runtime errors: Invalid inputs like division by zero, negative factorials, or out-of-range array indices can cause crashes.
Improves program correctness: Ensures that outputs match expected results.
Enhances security: Prevents buffer overflows and other vulnerabilities that may be exploited by malicious input.
Improves user experience: Provides clear prompts and allows users to correct mistakes instead of crashing the program.
When reading integers using scanf, check its return value to ensure proper input:
int num;
printf("Enter an integer: ");
if(scanf("%d", &num) != 1) {
printf("Invalid input. Please enter an integer.\n");
}
scanf returns the number of successfully read inputs.
If it does not match the expected count, the input is invalid.
To restrict values to a specific range:
if(num < 1 || num > 100) {
printf("Number must be between 1 and 100.\n");
}
Floating-point numbers are validated similarly:
float value;
printf("Enter a decimal value: ");
if(scanf("%f", &value) != 1) {
printf("Invalid input. Please enter a numeric value.\n");
}
Range checks can also be applied to floating-point numbers.
Character input is often used for menu options or Yes/No choices:
char option;
printf("Enter option (Y/N): ");
scanf(" %c", &option); // Space ignores leftover newline
if(option != 'Y' && option != 'N') {
printf("Invalid option. Enter Y or N.\n");
}
The space before %c is essential to skip leftover characters in the input buffer.
You can loop until a valid character is entered:
while(option != 'Y' && option != 'N') {
printf("Invalid option. Enter Y or N: ");
scanf(" %c", &option);
}
Strings require careful handling to avoid buffer overflow:
char name[20];
printf("Enter your name (max 19 characters): ");
scanf("%19s", name);
The %19s ensures no more than 19 characters are read, leaving space for the null terminator.
For more reliable input, fgets can be used:
fgets(name, sizeof(name), stdin);
fgets reads until newline or buffer limit.
Remove the trailing newline if present:
name[strcspn(name, "\n")] = 0; // Remove newline
When input is invalid:
Prompt the user again until valid data is provided.
Clear the input buffer to remove leftover characters:
int c;
while((c = getchar()) != '\n' && c != EOF);
This prevents infinite loops caused by leftover invalid input.
int denominator;
printf("Enter denominator: ");
scanf("%d", &denominator);
while(denominator == 0) {
printf("Cannot divide by zero. Enter again: ");
scanf("%d", &denominator);
}
int choice;
printf("Enter a number between 1-3: ");
scanf("%d", &choice);
while(choice < 1 || choice > 3) {
printf("Invalid choice. Enter 1, 2, or 3: ");
scanf("%d", &choice);
}
char input[10];
printf("Enter a string (max 9 characters): ");
scanf("%9s", input);
int age;
printf("Enter age (0-120): ");
scanf("%d", &age);
while(age < 0 || age > 120) {
printf("Invalid age. Enter again: ");
scanf("%d", &age);
}
int marks;
printf("Enter marks (0-100): ");
while(scanf("%d", &marks) != 1 || marks < 0 || marks > 100) {
printf("Invalid input. Enter a number between 0-100: ");
while(getchar() != '\n'); // Clear buffer
}
Assume all user input may be incorrect.
Use loops to repeatedly prompt for valid input.
Clear input buffer after invalid attempts.
Validate all types of input, not just numbers or strings.
Avoid unsafe functions like gets; prefer bounded scanf or fgets.
Combine type checking with range or length checks.
Modularize validation: Create functions for repeated validation tasks, like reading integers, floats, or menu options.
Input validation ensures programs receive correct, safe, and expected data.
Numeric, character, and string inputs each require careful checks.
Validation prevents runtime errors, incorrect results, and security risks.
Use loops, buffer clearing, and bounds checking for robust input handling.
Proper validation improves program reliability, correctness, and user experience.
Write a program to read an integer from the user and ensure it is between 1 and 100. Keep prompting until valid input is entered.
Create a program that asks for a floating-point number and validates that it is non-negative.
Write a program to read a single character input (‘Y’ or ‘N’) and reject any other entries until valid input is given.
Create a program to input a string (max 20 characters) for a username. Ensure the input does not exceed the limit.
Write a program to input a student’s age. Accept only values between 5 and 120.
Write a program to input marks of a student (0-100) and validate both the type and range of the input.
Create a program to read an array of 5 integers from the user. Validate that each input is numeric.
Write a program to input a denominator for division. Ensure it is not zero before performing the division.
Create a program that asks the user for a menu choice (1-4). Keep prompting until a valid option is entered.
Write a program to input a full name using fgets, and remove the trailing newline character if present. Validate that the string is not empty.