0

I have a problem with function which gets coordinates, from user, equal or bigger than 0 and lower than certain value M (M, x, y are ints). When I put only itegers everything is fine, but when i type two or one char my loop goes to infinity without asking to type again these coordinates.

My code:

 do {
        cout << "\t" << "Give coordinates in following format: X Y." << endl;
        cout << "\t";
        cin >> y >> x;
    } while (x < 0 || x > M || y < 0 || y > M);
ViperPG
  • 41
  • 4
  • 2
    [Why would we call cin.clear() and cin.ignore() after reading input?](https://stackoverflow.com/a/5131654) – 001 Jun 08 '21 at 16:41
  • 1
    _but when i type two or one char my loop goes to infinity_ Yes. Wrong input will cause that the stream (`std::cin` in your case) goes into fail state. In this case, you have to clear the fail state and to ignore the wrong input. Otherwise it will fail again and again and never come out (but this is what you already realized). – Scheff's Cat Jun 08 '21 at 16:42

1 Answers1

2

std::cin has something that is called a "fail" state. If you try to input something other than the value of expected type, std::cin will enter said fail state, and will no longer receive input, hence it not waiting for you to provide it with values.

You can check if it has entered fail state with: cin.fail(), which returns True if it has entered fail state.

You can clear the failed state with cin.clear().

f4pl0
  • 21
  • 1