example3_err_input_validation.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <limits>

int main() {
    int number;

    while (true) {
        std::cout << "Enter a positive integer: ";
        std::cin >> number;

        if (std::cin.fail() || number <= 0) {
            std::cerr << "Invalid input. Please try again." << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        } else {
            break;
        }
    }

    std::cout << "You entered: " << number << std::endl;

    return 0;
}
Back to input-output