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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?