Re: cin.fail() , ignore() , clear()...
On Feb 9, 11:24 pm, TheGunslinger <mikiesrunsbaal....@sbcglobal.net>
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.
I'm not sure what you mean by "most effective" (and I can easily
enter text for which it would fail), but it certainly looks like
serious abuse of exceptions. If I could afford to ignore end of
file and possible hard errors, I'd use something like:
int
getInt( std::istream& source )
{
int result;
source >> result;
while ( !source ) {
source.clear();
source.ignore(INT_MAX, '\n');
source >> result;
}
return result;
}
A more realistic version would be:
Fallible<int>
getInt( char const* promptInCaseOfError, std::istream& source )
{
Fallible<int> result;
bool fatalErrorSeen = false;
while ( !fatalErrorSeen && !result.isValid() ) {
int tmp;
source >> tmp;
if ( source ) {
result.validate( tmp );
} else if ( source.bad() || source.eof() ) {
fatalErrorSeen = true;
} else {
source.clear();
source.ignore( INT_MAX, '\n' );
if ( promptInCaseOfError != NULL ) {
std::cout << prompt;
std::cout.flush();
}
}
}
return result;
}
--
James Kanze
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]