views:

39

answers:

1

Why is my cin being skipped in the following while?

int main() {
        int option;
        cin >> option;
        while(!cin.good()) {
                cout << "Looping" << endl;
                cin >> option;
        }
}
+2  A: 

Errors in iostreams are sticky. You need to clear the error state before cin works again.

int main() {
        int option;
        cin >> option;
        while(!cin.good()) {
                cout << "Looping" << endl;
                cin.clear(); // ignore erroneous line of input:
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cin >> option;
        }
}
Potatoswatter
Will
@Will: `max` is a function; note the parentheses after it.
Potatoswatter