When the reading fails, you set valid
to false
, so the condition in the while
loop is false
and the program returns input
(which is not initialized, by the way).
You also have to empty the buffer before using it again, something like:
#include <iostream>
#include <limits>
using namespace std;
double read_input()
{
double input = -1;
bool valid= false;
do
{
cout << "Enter a number: " << flush;
cin >> input;
if (cin.good())
{
//everything went well, we'll get out of the loop and return the value
valid = true;
}
else
{
//something went wrong, we reset the buffer's state to good
cin.clear();
//and empty it
cin.ignore(numeric_limits<streamsize>::max(),'
');
cout << "Invalid input; please re-enter." << endl;
}
} while (!valid);
return (input);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…