Question

        while(cout << "How many elements do you want: " && !(cin >> el))
        {
            cin.sync();
            cin.clear();
            cout << " Invalid input!\n";
        }

el is an int, when I typed a character, the loop goes infinite. I followed one of the posts in SO to fix bad input, but it is not working, it goes infinite loop printing "How many elements do you want: Invalid input!" I tried ignore(10000, "\n") as well, but still not working...

Était-ce utile?

La solution

When an error occurs when reading from a stream, an error flag gets set and no more reading is possible until you clear the error flags.

That's why you get an infinite loop.

Instead use :

cin.clear();  // clears the error flags  
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Autres conseils

Perform cin.clear() before cin.sync(). It works for me.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top