Ok, I'll try to simplify the other example and explain more.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string str;
bool entered_int;
while (true)
{
entered_int=true;
cout << "enter an int: ";
cin >> n;
if (!cin.good())
{
entered_int=false;
cin.clear();
getline(cin,str);
}
else
{
getline(cin,str);
if (str!="") entered_int=false;
}
if (entered_int) break;
else cout << "you did not enter an int..." << endl;
}
cout << "\n(hit enter to quit...)" << endl;
cin.get();
return 0;
}
|
The while statement above loops until you enter an integer.
Let's see how exactly it works by carefully studying some input cases...
Suppose we enter
asdf. This causes the
cin >> n;
statement to alter
the internal state of cin so that
cin.good()
returns
false
,
and leaves the "asdf" string in the input buffer (meaning, it will be
the first thing encountered by the next input operation).
We have to do two things to rectify the situation:
(1) clear cin's internal state so that it can be used for input again (
cin.clear();
)
(2) remove the "asdf" string from the input buffer (
getline(cin,str);
)
At this point entered_int is
false
, so we keep looping.
Next, suppose we enter
123 asdf. Now, n is set to 123 and cin's state is unaltered
(
cin.good()
returns
true
), but we have a " asdf" string sitting in the buffer.
We don't want that. We remove it using
getline(cin,str);
, and then check
wether or not the string we got is empty. In this case it's not (it's " asdf"),
so, once more, entered_int is set to
false
and we keep looping.
Finally, we enter
123. n is set to 123, cin's state is unaffected and str is an empty string.
This means that entered_int is
true
, so we stop looping.