Modern C++ • C++20 baseline
Console Input and Validation
Read input into typed values and handle malformed input instead of trusting the stream.
Formatted extraction is convenient for small console programs, but it can fail when input does not match the requested type. Check the stream state before using the value. For untrusted or complicated input formats, read a line first and parse it with an API that reports exactly where conversion stopped.
Key points
- A failed stream remains in a failed state until it is cleared.
- Input validation is separate from successful token extraction.
Example
#include <iostream>
int main() {
int quantity{};
std::cout << "Quantity: ";
if (!(std::cin >> quantity) || quantity < 0) {
std::cerr << "Enter a non-negative whole number.\n";
return 1;
}
std::cout << "Accepted: " << quantity << '\n';
}
What to expect
Input 5 prints “Accepted: 5”; malformed or negative input is rejected.
Practice exercise
Try text, a negative number, and an excessively large number. Decide how your application should respond to each.
Key idea: Check both conversion success and domain rules before acting on user input.