When you input a string value, operator>>
tries to extract your string input into variable 'number'. This fails since string cannot be converted into unsigned int. This wrong input value is then left in the buffer, while std::cin
fails. Any future inputs for extraction will also fail silently. To get past this use,
#include <limits>
if (std::cin.fail()) // has input extraction failed?
{
std::cin.clear(); // then clear cin and reset it
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //clear buffer
}
std::cin.ignore()
takes in two parameters - the first one is number of characters to remove and the second is the parameter until which to remove characters from the buffer.
std::numeric_limits<std::streamsize>::max()
just gives the largest value that can be stored in type std::streamsize
. You can just use a value like 200 or 300, but if the user has somehow input more values, using std::numeric_limits
would help guard against this possibility. Add this check in the appropriate place in your code.