|
| 1 | +#include <iostream> |
| 2 | +#include <limits> |
| 3 | +#include <string> |
| 4 | + |
| 5 | +int readIntInRange(const std::string& label, int minValue, int maxValue) { |
| 6 | + int value = 0; |
| 7 | + |
| 8 | + while (true) { |
| 9 | + std::cout << label; |
| 10 | + if (!(std::cin >> value)) { |
| 11 | + std::cout << "Invalid input type. Please enter an integer.\n"; |
| 12 | + std::cin.clear(); |
| 13 | + std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |
| 14 | + continue; |
| 15 | + } |
| 16 | + |
| 17 | + if (value < minValue || value > maxValue) { |
| 18 | + std::cout << "Value must be between " << minValue << " and " << maxValue << ".\n"; |
| 19 | + std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |
| 20 | + continue; |
| 21 | + } |
| 22 | + |
| 23 | + std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |
| 24 | + return value; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +double readDoubleInRange(const std::string& label, double minValue, double maxValue) { |
| 29 | + double value = 0.0; |
| 30 | + |
| 31 | + while (true) { |
| 32 | + std::cout << label; |
| 33 | + if (!(std::cin >> value)) { |
| 34 | + std::cout << "Invalid input type. Please enter a decimal number.\n"; |
| 35 | + std::cin.clear(); |
| 36 | + std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |
| 37 | + continue; |
| 38 | + } |
| 39 | + |
| 40 | + if (value < minValue || value > maxValue) { |
| 41 | + std::cout << "Value must be between " << minValue << " and " << maxValue << ".\n"; |
| 42 | + std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |
| 47 | + return value; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +int main() { |
| 52 | + const int age = readIntInRange("Enter your age (1-120): ", 1, 120); |
| 53 | + const double gpa = readDoubleInRange("Enter your GPA (0.0-4.0): ", 0.0, 4.0); |
| 54 | + |
| 55 | + std::cout << "\nValidated input summary:\n"; |
| 56 | + std::cout << "Age: " << age << '\n'; |
| 57 | + std::cout << "GPA: " << gpa << '\n'; |
| 58 | + |
| 59 | + return 0; |
| 60 | +} |
0 commit comments