开发者

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


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); 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜