You don't need to check the data before putting it into the stringstream, nor do you need to trim whitespace because the stream extraction operator
>>
does all that for you automatically, and it updates the state of the stream to a failure/bad state if the conversion fails.
stringstreams have an implicit cast to operator
void* which can be used to indicate success-vs-failure (NULL for failure, non-NULL for success). Note, when a stream fails, you need to
clear()
its error flags before you can reuse it again.
All you really need to do to validate any conversion from a string is:
1 2 3 4 5 6 7 8 9 10
|
bool convert( const std::string& from, int& to )
{
bool success( false );
std::istringstream buffer( from );
if ( buffer >> to )
{
success = true;
}
return success;
}
|
You could actually make it a template, since it would work for other types too.
So all you should need to do when interacting with the user is something along these lines
1 2 3 4 5 6 7
|
std::string input;
std::getline( std::cin, input );
int n;
if( convert( input, n ) )
{
}
|
(Deliberately excluding the while loop and min/max check to show the conversion usage)