Reading and Validating Input
Input functions can fail, so production code must test their result instead of assuming valid data.
What is Reading and Validating Input?
Input functions can fail, so production code must test their result instead of assuming valid data.
Read user input and reject invalid values.
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
main.c
#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
C++
main.cpp
#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
C exposes small procedural APIs and makes representation details explicit.
C++
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.