Re: cin.fail() , ignore() , clear()...
On 2011-02-09 15:24, TheGunslinger wrote:
I finally went with the following code snippet:
//-------------------------------------
do{
try{
cout<<"How many days to be rented?\n";
cin>>daysRented;
if(cin.fail()){
throw false;
}else{goodInput=true;}
}catch(bool IOerror){
goodInput=false;
cin.clear();
cin.ignore(20,'\n');
} //End try/throw/catch
}while(goodInput==false);
//--------------------------------------
which was most effective in catching bad user input errors.
It's not a good practice to throw an exception and catch it locally;
exceptions are better suited when you don't know from the throwing site
who will catch the exception and handle it.
The code snippet above can be rephrased in a much simpler form:
while (true) {
cout << "How many days to be rented?\n";
if (cin >> daysRented) // true iff !cin.fail()
break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
These are fine in a usual interactive setting, but when the user hits
EOF (Ctrl+D on Unix, Ctrl+Z on Windows) or when the input is redirected
from a file whose EOF is hit, you get an infinite loop.
So this is better:
while (true) {
cout << "How many days to be rented?\n";
if (cin >> daysRented) // true iff !cin.fail()
break;
if (cin.eof()) {
// It depends what you can do here,
// but let's assume it's meaningless to continue:
abort();
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
In summary, if you want a "keep-asking-until-valid" behaviour,
you always have to consider three cases:
(a) A good input was read. - break; keep going
(b) A bad input was read. - clear stream and retry input
(c) No input was read. (EOF) - stop and exit to a higher layer
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]