I have this condition for restricting inputs besides integers between 0-7. The purpose of this code is really to block out letters. Now I need to do something similar when the possible inputs are integers between 0-255.
Using clear()/ignore() is useful only in case of an erroneous input. Only when the wrong type (character like 'A' instead of integer) is entered. See this for an example how to correctly use it:
The correct syntax would be if (index != 0 || index != 1 || index != 2 || ...), but this would be logically wrong / always true (use && instead of ||).
Do not use clear()/ignore() if the stream does not report an error.
The reason that I used the index if statement the way I did was because I was getting an infinite loop if the input was a character. That if statement did resolve that issue. The current issue is that I need to prevent an infinite loop at the next stage (where the user is prompted to enter an integer between 0-255).
bool error = false;
int index = -1;
do {
if (error)
{
cout << "\nInvalid index, please try again!" << endl;
cin.clear();
cin.ignore(100, '\n');
}
cout << "Enter buffer index (0-7): ";
cin >> index;
if (!cin || index <0 || index > 7)
{
error = true;
}
else
{
error = false;
}
} while (error);
error = false;
int num = -1;
do {
if (error)
{
cout << "\nInvalid option, please try again!" << endl;
cin.clear();
cin.ignore(100, '\n');
}
cout << "buffer[" << index << "] = ";
cin >> num;
error = (!cin || num < 0 || num > 255);
} while (error);
switch (index)
{
case 0: index0 = num; break;
case 1: index1 = num; break;
case 2: index2 = num; break;
case 3: index3 = num; break;
case 4: index4 = num; break;
case 5: index5 = num; break;
case 6: index6 = num; break;
case 7: index7 = num; break;
}
The first time the loop is executed, at line 5 the error flag will be false, so the code inside the if statement will not be executed. After the cin at line 13, a check is made for failed input (non-numeric characters) or out of range value being entered. The error flag is set accordingly. The loop will repeat until correct input is entered.
The second block of code from line 27 to 41 is similar. Here I used a more concise assignment statement at line 39. This works exactly the same as the if/else in the earlier code, but is less verbose.
Finally, the original code had a lot of repetition, which I've cut down to the switch-case at line 44 to 54. Actually I would replace all the separate variables index0 to index7 with an array value[8] and then that block becomes simply the single line