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());
CodePudding user response:
You must add the line
std::cin.clear();
immediately before the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
otherwise the call to std::cin.ignore
will fail, because the stream is in a failed state.
However, this will cause the loop condition of the outer loop to not work. Therefore, the entire code should be changed to the following:
double input;
while( true ) {
std::cout << "Enter a double value : ";
std::cin >> input;
if ( std::cin.fail() ) {
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::cout << "Invalid input!\n";
continue;
}
//input is ok, so break out of infinite loop
break;
}