Input Validation
What happens on bad input?
int age;
std::cin >> age; // user types "abc"
- The extraction fails:
ageis set to 0 std::cinenters a fail state: every later>>does nothing- The bad characters stay in the buffer
Checking for failure
if (std::cin >> age) { /* success */ }
if (std::cin.fail()) { /* failed */ }
Recovering: clear + ignore
std::cin.clear(); // 1. reset the error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 2. throw away the bad line
A reusable validation loop
int read_int(const std::string& prompt, int min, int max) {
int value;
while (true) {
std::cout << prompt;
if (std::cin >> value && value >= min && value <= max) {
std::cin.ignore(..., '\n');
return value;
}
if (std::cin.eof()) throw ...; // no more input at all
std::cout << "Invalid, try again\n";
std::cin.clear();
std::cin.ignore(..., '\n');
}
}
Things to validate
- Type: is it a number?
- Range: age 1–120, month 1–12, amount > 0
- Whole input: "12abc" —
>>reads 12 and leaves "abc"! Reading the full line and checking that nothing is left over catches this - End of input: handle
eof()to avoid infinite loops
Line-based validation ✅ (most robust)
std::getlinethe whole line- Convert with
std::stoi/std::from_chars(<charconv>) and check that all characters were used - Check the range
std::from_chars (C++17) is fast, doesn't throw, and reports where parsing stopped.
Example
#include <charconv>
#include <iostream>
#include <limits>
#include <optional>
#include <string>
// Parse a whole string as an int; reject "12abc", "", "abc"
std::optional<int> parse_int(const std::string& s) {
int value{};
auto [end, error] = std::from_chars(s.data(), s.data() + s.size(), value);
if (error != std::errc{} || end != s.data() + s.size()) return std::nullopt;
return value;
}
int read_int(const std::string& prompt, int min, int max) {
std::string line;
while (true) {
std::cout << prompt;
if (!std::getline(std::cin, line)) return min; // input ended: fall back
auto value = parse_int(line);
if (!value) std::cout << "\"" << line << "\" is not a whole number\n";
else if (*value < min || *value > max) std::cout << *value << " is out of range " << min << "-" << max << '\n';
else return *value;
}
}
int main() {
int month = read_int("Month (1-12): ", 1, 12);
std::cout << "You chose month " << month << "\n\n";
// The >> way: detect the fail state and recover
int amount;
std::cout << "Amount: ";
std::cin >> amount;
if (std::cin.fail()) {
std::cout << "\nNot a number (amount was set to " << amount << "), recovering...\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Amount again: ";
if (std::cin >> amount) std::cout << "\nGot Rs. " << amount << '\n';
return 0;
}
/* Output:
Month (1-12): "abc" is not a whole number
Month (1-12): "12abc" is not a whole number
Month (1-12): 13 is out of range 1-12
Month (1-12): You chose month 11
Amount:
Not a number (amount was set to 0), recovering...
Amount again:
Got Rs. 2500
*/