Skip to content

Instantly share code, notes, and snippets.

@timofurrer
Created May 18, 2012 15:11
Show Gist options
  • Save timofurrer/2725779 to your computer and use it in GitHub Desktop.
Save timofurrer/2725779 to your computer and use it in GitHub Desktop.
C++ convert string to every type using template function
template <typename T>
T ConvertString( const std::string &data )
{
if( !data.empty( ))
{
T ret;
std::istringstream iss( data );
if( data.find( "0x" ) != std::string::npos )
{
iss >> std::hex >> ret;
}
else
{
iss >> std::dec >> ret;
}
if( iss.fail( ))
{
std::cout << "Convert error: cannot convert string '" << data << "' to value" << std::endl;
return T( );
}
return ret;
}
return T( );
}
@CyberShadow
Copy link

Doesn't work for char or aliases like uint8_t, instead of decimal conversion reads and returns one character.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment