cin >> red_rgb;
How to check the red_rgb, green_rgb, blue_rgb variable when entering it, so that only values in the range from 0 to 255 are allowed, while only integers {0,1,2...254,255} are counted, otherwise, you will need to enter the correct value.
int red_rgb = 0;
int green_rgb = 0;
int blue_rgb = 0;
std::cout << "Enter R: ";
while (!(cin >> red_rgb) || !(red_rgb >= 0 && red_rgb <= 255))
{
cout << "Error";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
std::cout << "Enter G: ";
while (!(cin >> green_rgb) || !(green_rgb >= 0 && green_rgb <= 255))
{
cout << "Error";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
std::cout << "Enter B: ";
while (!(cin >> blue_rgb) || !(blue_rgb >= 0 && blue_rgb <= 255))
{
cout << "Error";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
This method tests for a range, but skips semicolons. And if you enter letters instead of numbers, the more letters there are, the more times the cycle will start.
if you enter a float, the cycle for entering the next value is skipped enter image description here
CodePudding user response:
Try something like that:
int inprgb(const string& hint){
int a=-1;
while (true){
cout << hint;
cin>>a;
if (cin.fail() || cin.peek()!=10 ||!(a >= 0 && a <= 255) ) {
cin.clear();
cout << "Error\n";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
break;
}
return a;
};
and
red_rgb = inprgb("Enter R: ");