Skip to content

Instantly share code, notes, and snippets.

@fstamour
Last active December 13, 2015 20:48
Show Gist options
  • Save fstamour/4972675 to your computer and use it in GitHub Desktop.
Save fstamour/4972675 to your computer and use it in GitHub Desktop.
Basic utility functions to validate user input.
#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