Skip to content

Instantly share code, notes, and snippets.

@fstamour
Last active December 16, 2015 11:39
Show Gist options
  • Save fstamour/5429114 to your computer and use it in GitHub Desktop.
Save fstamour/5429114 to your computer and use it in GitHub Desktop.
Function to read an integer OR a float from a std::istream.
///@return true if int, false if float
bool readIntOrNotFloat( std::istream& in, int& i, float& f ) {
in >> i;
if( in.good() ) {
char c = in.peek();
if( c == '.' ) {
in >> f;
f += i;
return false;
}
}
return true;
}
int i = 0;
float f = 0;
bool bool int_or_notFloat = 42; //Always a good thing to init a varaible...
cout << "Enter an integer or a float (anything else to exit)\n";
while(cin) {
cout << "? ";
int_or_notFloat = readIntOrNotFloat(cin, i, f);
if(cin) {
if( int_or_notFloat ) {
cout << "Got an integer: " << i << endl;
} else {
cout << "Got a float: " << f << endl;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment