-4

I stumbled upon this infinite loop. I was supposed to check the user's input not to be of any type other than integer and also not to be a negative number. Why am I getting this infinite loop and more importantly how do I impose these restrictions on the input?

#include <iostream>
using namespace std;

int main(){
    long long int m, k;
    cin >> m >> k;
    while (cin.fail() || m < 0 || k < 0){
        cin.clear();
        cout << "please enter another input";
        cin >> m >> k;
    }

return 0;
}
Drise
  • 4,310
  • 5
  • 41
  • 66
CtrlMj
  • 119
  • 7

2 Answers2

2

If operator >> fails due to input not matching the target type, the characters remain in the stream (even if you clear the fail bit). So if you repeat the same read operation again and again, it will fail again and again. Usually you will skip/ignore characters in such a case. The following example is directly taken from cppreference/ignore:

int main()
{
    std::istringstream input("1\n"
                             "some non-numeric input\n"
                             "2\n");
    for(;;) {
        int n;
        input >> n;

        if (input.eof() || input.bad()) {
            break;
        } else if (input.fail()) {
            input.clear(); // unset failbit
            input.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
        } else {
            std::cout << n << '\n';
        }
    }
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
1

IF cin.fail() is true - we are good to go for the loop

After the first attempt of reading two numbers that failed, you clear the status and try again. This is without reading the offending item. It is bound to fail again as the data is left in the stream.

You need to add logic that on failure of reading, you take the appropriate action - like reading the offending data

Ed Heal
  • 59,252
  • 17
  • 87
  • 127