Skip to content

Instantly share code, notes, and snippets.

@sim642
Created September 13, 2011 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sim642/1213875 to your computer and use it in GitHub Desktop.
Save sim642/1213875 to your computer and use it in GitHub Desktop.
Input validation
#include <iostream>
#include <limits>
using namespace std;
template<typename T>
bool valid_input(istream &stream, T &value)
{
bool good = true;
stream >> value;
if (!stream || stream.peek() != '\n')
{
good = false;
}
if (!good)
{
stream.clear();
stream.ignore(numeric_limits<streamsize>::max(), '\n');
}
return good;
}
int main()
{
int n;
while (cout << "Enter a fucking number: ", !valid_input(cin, n))
{
cout << "Not a fucking number!" << endl;
}
cout << "Your number was " << n << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment