Last active
December 16, 2015 11:39
-
-
Save fstamour/5429114 to your computer and use it in GitHub Desktop.
Function to read an integer OR a float from a std::istream.
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
///@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; | |
} |
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
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