I'm experiencing an infinite loop in a simple and tiny C++ code where I try to read user input and repeat when input fails until it correctly fills an integral type:
std::size_t size{};
while (std::cout << "Enter size: " && !(std::cin >> size))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << std::endl;
}
But despite clearing std::cin
and ignoring buffer contents, the loop gets running infinitely without prompting for user input.
What am I missing?
What should be done to make std::cin
block io and read user input in each iteration after it fails?