Hi! I am creating a program that uses arrays. I'm struggling in one area when a user puts an incorrect input (like a letter), I don't know where the code should be placed, or what it is. Currently, when I place an incorrect value, it is stuck in an endless loop.
The if statement at line 71 is missing its opening and closing {}s.
Line 101 will exit the program. the "1" denotes that there was a problem f some kind. Since this case statement is in main a "return 0;" will work fine. Also line 102 will never be reached because of the exit or return.
Line 71. You check if "cin" has failed, but you check is for only one of the state bits and this may not always get set. At least it is best not to count on this. A better choice is if (!cin).
What you could do is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
for (int i = 0; i < 10; i++)
{
cin >> arr[i];
while (!cin)
{
std::cout << "An error message" << std::endl;
std::cin.clear(); // <--- Resets the state bits.
std::cin.ignore(30000, '\n'); // <--- Clears the input buffer.
std::cin >> arr[i];
}
}
This will eliminate the need for line 71.
The same code could also follow line 81.
I will need to load up the code to see if i can see anything else.