Reading and Validating Input
Read user input and reject invalid values.
What is Reading and Validating Input?
Input functions can fail, so production code must test their result instead of assuming valid data.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
#include <stdio.h>
int main(void) {
int age;
printf("Age: ");
if (scanf("%d", &age) != 1 || age < 0) {
puts("Invalid age");
return 1;
}
printf("Next year: %d\n", age + 1);
return 0;
}
Age: 20
Next year: 21
#include <iostream>
int main() {
int age;
std::cout << "Age: ";
if (!(std::cin >> age) || age < 0) {
std::cerr << "Invalid age\n";
return 1;
}
std::cout << "Next year: " << age + 1 << '\n';
}
Age: 20
Next year: 21
C and C++ comparison
scanf returns the number of successfully converted fields. std::cin enters a failed state when extraction cannot satisfy the requested type.
C exposes small procedural APIs and makes representation details explicit.
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Average of Three Average three whole numbers. Easy
- Rectangle Perimeter Compute the perimeter of a rectangle from its sides. Easy