Created
September 13, 2011 14:04
-
-
Save sim642/1213875 to your computer and use it in GitHub Desktop.
Input validation
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
#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