I'm trying to find a way to keep asking for user input even after an invalid input is taken by using std::cin.fail()
. However, when the input is invalid, the program simply runs in a loop and does not pause on std::cin even with std::cin.ignore()
.
I tried moving std::cin.ignore()
to before the std::cin >> input
and although it does work, the program first stops at the std::cin.ignore()
line (requiring an input first that won't be used) before going to the std::cin
input line which is not what I want(I want it to immediately ask for input).
Is there a reason why and how do I fix it?
double input;
do {
std::cin.clear();
std::cout << "Enter a double value : ";
std::cin >> input;
if (std::cin.fail()) {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input!\n";
}
} while (std::cin.fail());