Last active
December 13, 2015 20:48
-
-
Save fstamour/4972675 to your computer and use it in GitHub Desktop.
Basic utility functions to validate user input.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef MP_BASIC_USER_INPUT | |
#define MP_BASIC_USER_INPUT | |
namespace mp { | |
template< typename T > | |
bool validateInput( std::istream& is, T& value ) { | |
std::istream::sentry isOk(is); | |
if( isOk ) { | |
is >> value; | |
} else { | |
throw std::runtime_error("An error occured with a std::istream."); | |
} | |
return is; | |
} | |
void flush( std::istream& is ) { | |
while( is.good() && is.get != '\n' ); | |
} | |
template< typename T > | |
void promptUntilValidInput( std::string prompt, T& value ) { | |
using namespace std; | |
bool entreValide = false; | |
while( !entreValide ) { | |
cout << prompt; | |
entreValide = validateInput( cin, value ); | |
if( !entreValide ) { | |
cin.clear(); | |
flush( cin ); | |
} | |
} | |
flush( cin ); | |
} | |
} //namespace mp | |
#endif //MP_BASIC_USER_INPUT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment