C++ Loop logic / cin.ignore() stalling loop

Viewed 33

I'm trying to figure out the logic for a user who has to enter a three digit integer (x). This integer or integers go into a another container class hence the need for place.insert(x);. If user enters -1 then the method should stop taking in input. For some reason if I do not put a delimiter or anything inside of cin.ignore() it just stalls the program. If I put cin.ignore(10000,'\n') it will clear it but when I enter in a new number ie "222", in the debugger it shows "22" instead. (Would like to know why that is also!) For the while condition I use (x != -1 && x < 100 || x > 999) but is that redundant because x can be -1...? I do not want to use break and would like to know if there is a way to make this work or even a better logic that I should be implying. I'm trying to have it be able to validate if user enters "dlsfjd" or even just "z" and or anything higher or lower than 3 digits.

    int x;

    do {
        cin >> x;

        if (cin.fail() || x < 100 || x > 999) {
            cout << "Input failed. Please try again: ";
            cin.clear();
            cin.ignore();
        } else
            place.insert(x);

    } while(X != -1 && X < 100 || X > 999);
0 Answers
Related