This causes problems due to extra whitespace:
std::string t("3.14 ");
double d = boost::lexical_cast<double> (t);
So, I wrote this
template<typename T>
T string_convert(const std::string& given)
{
T output;
std::stringstream(given) >> output;
return output;
}
double d = string_convert<double> (t);
What can be the problems with this? Is there a better way? Much prefer to use lexical cast
Note that your code isn’t always correct. If you do
string_convert<double>("a"), for example, the read will fail and you’ll returnoutputuninitialized, leading to undefined behavior.You can do this:
Note the only difference between the above code and Boost’s is that Boost also checks to make sure nothing is left in the stream. What you should do, though, is just trim your string first: