If you are going to validate input you need to consider the case when a user enters invalid input. For example what would happen if the user enters a K instead of a number? so if you have an integer variable
int loan = 0;
and you do
cin >> loan;
if the user enters k, input will fail so the value of loan will not change and cin will enter a fail state. The k will still be waiting for input so if we
cin >> loan;
again it will fail for two reasons cin is in an error state and because k is not an integer.
lets look at an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int loan = 0;
cout << "Enter amount of loan :";
while (!(cin >> loan) || loan < 0)
{
cin.clear(); //removes any error flags
cin.ignore(numeric_limits<streamsize>::max(), '\n');//removes bad input
std::cout << "Invalid input please try again" << std::endl;
cout << "Enter amount of loan :";
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::cout << "loan " << loan << std::endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return 0;
}
|
ok so line 9 in the above code
while (!(cin >> loan) || loan < 0)
needs to be explained a bit. take this portion !(cin >> loan) here we attempt to get an integer from cin. The >> operator returns its left hand operand. so after this statement executes we have something that looks like this
while (!(cin) || loan < 0)
ok so what does !(cin) do ? it checks the stream to see if any error flags are set. Meaning if cin is good ie. its not in an error state it will return 1 and if its not good meaning it is in an error state than it will return 0. If 0 is returned that means there was a problem and we need to deal with that. By doing !(cin) the 0 returned by cin is changed to a 1 and causes the wile loop to execute where we handle the problem.
When cin is in an error state all input attempts fail, so we need to clear the error flags. On line 11 we do
cin.clear(); //removes any error flags
this removes any error flags and takes us out of the fail state. However, the input that caused the error state is still waiting to be input because we failed to input it the first time. So we need to remove this input because it will just cause us to fail again. That's where
cin.ignore(numeric_limits<streamsize>::max(), '\n');//removes bad input
comes in on line 12 this removes everything up to and including a newline. now that the bad input is cleared we can try to input again.