How do I sanitize inputs and outputs with ranges?

Sanitizing inputs and outputs is crucial in C++ to ensure that data falls within specified ranges, particularly when dealing with user inputs or external data sources. This helps to prevent errors and security vulnerabilities in your applications.

Here's an example of how you can sanitize user input by checking if it falls within a predefined range:

#include #include int main() { int input; // Set a valid range const int minRange = 1; const int maxRange = 100; std::cout << "Enter a number between " << minRange << " and " << maxRange << ": "; while (true) { std::cin >> input; // Check if input is valid if (std::cin.fail() || input < minRange || input > maxRange) { std::cin.clear(); // clear error flag std::cin.ignore(std::numeric_limits<:streamsize>::max(), '\n'); // ignore invalid input std::cout << "Invalid input. Please enter a number between " << minRange << " and " << maxRange << ": "; } else { break; // input is valid } } std::cout << "You entered: " << input << std::endl; return 0; }

C++ input validation sanitize inputs range checking data sanitization