Heh, this is an old question that could use a better answer.
User input should be received as a string , and then converted in error to the desired data type. Conveniently, it also allows you to answer questions like "what data type is my input?"
Here is a function that I use a lot. Other options exist, for example, in Boost, but the basic premise is the same: try to convert type string → and watch for success or failure:
template <typename T> std::optional <T> string_to( const std::string& s ) { std::istringstream ss( s ); T result; ss >> result >> std::ws;
Using the optional type is one way. You can also throw an exception or return the default value on failure. Whatever works for your situation.
Here is an example of its use:
int n; std::cout << "n? "; { std::string s; getline( std::cin, s ); auto x = string_to <int> ( s ); if (!x) return complain(); n = *x; } std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
restrictions and type identification
To do this, of course, there must be a method to uniquely extract your data type from the stream. This is the natural order of things in C ++, that is, business as usual. So no surprises here.
The next caveat is that some types combine others. For example, if you are trying to distinguish between int and double , check int first, since everything that converts to int is also double .
source share