you can use this template function, but this is not just for converting a string to an int - it is to convert a string to every type:
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( );
}
If you want to now if the convert was successfull, then return a specific value in the if iss.fail()
or pass a second reference argument to the function and set the value to false if it failed.
You can use it like this:
uint16_t my_int = ConvertString<uint16_t>("15");
If you like the solution with the reference argument, here an example:
#include <iostream>
#include <sstream>
#include <string>
#include <inttypes.h>
template <typename T>
T ConvertString(const std::string &data, bool &success)
{
success = true;
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())
{
success = false;
return T();
}
return ret;
}
return T();
}
int main(int argc, char **argv)
{
bool convert_success;
uint16_t bla = ConvertString<uint16_t>("15", convert_success);
if(convert_success)
std::cout << bla << std::endl;
else
std::cerr << "Could not convert" << std::endl;
return 0;
}