0

I am trying to catch wrong inputs without the tryCatch-Block. Whenever the user types a wrong value(e.g. 'hh' or -5), my program shall ask again until the the user types in a correct value. Afterwards go on until the array is full.

int main() {
  double array[6];
  string str_array[7];
  str_array[0] = "stringA";
  str_array[1] = "stringB";
  str_array[2] = "stringC";
  str_array[3] = "StringD";
  str_array[4] = "StringE";
  str_array[5] = "StringF";
  str_array[6] = "StringG";
  double value;

  for (int i = 0; i < 7; i++) {
    bool exit = false;
    while (!exit) {
        cout << str_array[i] << ":";
        if (cin >> value&& value> 0) {
            array[i] = value;
            cout << array[i] << endl;
            exit = true;
        } else {
            cerr << "incorrect input" << endl;
            cin.clear();
        }
    }
  }
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190
moody
  • 404
  • 7
  • 19

1 Answers1

1
cin.clear();

isn't enough. You also need to consume the rejected input along to synchronize for new input:

else {
        cerr << "incorrect input" << endl;
        cin.clear();
        std::string dummy; // <<<<<
        cin >> dummy; // <<<<<
    }

Otherwise you will just read the rejected input over and over again.


Something like cin.ignore(numeric_limits<streamsize>::max(), '\n') might serve you as well.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190