I have the following loop. It should read numbers until EndOfFile
, or the user input -999
int arr[100];
int index;
for (index = 0; index < 100; index++)
{
cin >> arr[index];
if (!cin)
{
cin.clear();
index--;
continue;
}
if (arr[index] == -999)
{
break;
}
}
When the user input an invalid thing, such as some char
s, this loop is being repeated for ever without clear
ing the error state or stopping.
After calling
clear
, you've to somehow remove the invalid input from the stream. Here is one way:It's because when
cin
fails to read the invalid input, it remains there in the stream. It has to be removed, by some means. I just read and ignore it.You can also use
ignore
as:which is better in my opinion provided inputs are space separated (and if you don't want to inspect the invalid input). The online doc says: