-2

If we have multiple cin statements and one of them gets a wrong input, every following cin fails. How to prevent that?

#include <iostream>
using namespace std;

int main() {
    int a, b, c, d, e;
    cin>>a;
    cin>>b;
    cin>>c;
    cin>>d;
    cin>>e;
    return 0;
}

If I enter some string for first or any other variable that expects int, every cin that follows terminates. How to prevent this failure?

Pranjal Kaler
  • 483
  • 3
  • 14

1 Answers1

2

If you want to do something when it fails, wrap the above expression in an if statement.

if (!(std::cin >> a >> b >> c >> d >> e)) {
 // ...
}

It terminates because the stream is in a failed state. You'll have to clear the flags with clear() and continue parsing input.

If you want to know which input failed specifically:

int arr[] = {a, b, c, d};
for (int i=0; i<4; i++) {
  if (!(cin >> arr[i])) {
    // ... clean up and clear() if you want to continue
  }
}
David G
  • 94,763
  • 41
  • 167
  • 253