11

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 chars, this loop is being repeated for ever without clearing the error state or stopping.

1 Answers1

11

After calling clear, you must also somehow remove the invalid input from the stream. Here is one way:

 cin >> arr[index];
 if (!cin)
 {
  cin.clear();
  std::string ignoreLine; //read the invalid input into it
  std::getline(cin, ignoreLine); //read the line till next space
  index--;
  continue;
 }

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:

cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(),' ');

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:

istream::ignore

istream& ignore( streamsize n = 1, int delim = EOF );

Extract and discard characters

Extracts characters from the input sequence and discards them.

The extraction ends when n characters have been extracted and discarded or when the character delim is found, whichever comes first. In the latter case, the delim character itself is also extracted.

scohe001
  • 15,110
  • 2
  • 31
  • 51
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • @Mr.DDD: What invalid input your provide? – Nawaz Sep 14 '11 at 08:43
  • Your second version doesn't work. You are igonring `1024` characters or when `' '` is found. However, a user may not input space at the end, and the input will be contiued to 1024 characters! –  Sep 14 '11 at 08:46
  • @Mr.DDD: You can put some bigger value, instead of `1024`. – Nawaz Sep 14 '11 at 08:49
  • 1
    @Mr.DDD: That's good. But what if you've valid input on the same line just after the invalid input?By the way, you could use `std::numeric_limits::max()` instead of `1024`. – Nawaz Sep 14 '11 at 08:52
  • You've to edit your answer, since the space delim won't work until the user input space. User must press ENTER so that \n is found –  Sep 14 '11 at 08:53
  • @Mr.DDD: I just added `[...] provided inputs are space separated`. – Nawaz Sep 14 '11 at 08:56