Nikhil
Nikhil

Reputation: 2280

Problems due to extra whitespace in boost::lexical cast

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

Upvotes: 1

Views: 2587

Answers (2)

GManNickG
GManNickG

Reputation: 504333

Note that your code isn't always correct. If you do string_convert<double>("a"), for example, the read will fail and you'll return output uninitialized, leading to undefined behavior.

You can do this:

template<typename T> 
T string_convert(const std::string& given)
{
  T output;
  if (!(std::stringstream(given) >> output))
    throw std::invalid_argument(); // check that extraction succeeded

  return output;
}

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:

#include <boost/algorithm/string/trim.hpp>

std::string t("3.14 ");
boost::algorithm::trim(t); // get rid of surrounding whitespace

double d = boost::lexical_cast<double>(t); 

Upvotes: 6

Jerry Coffin
Jerry Coffin

Reputation: 490788

Boost::lexical_cast considers an attempted conversion successful only if the entire input is converted into the output. I.e., it's basically like your string_convert, except that just before return output, it checks whether there's anything left in the stringstream, and if there is, it considers the conversion "failed", and throws an exception.

Upvotes: 3

Related Questions