这会导致由于额外的空格问题:问题的boost ::词汇投
std::string t("3.14 ");
double d = boost::lexical_cast<double> (t);
所以,我写了这个
template<typename T>
T string_convert(const std::string& given)
{
T output;
std::stringstream(given) >> output;
return output;
}
double d = string_convert<double> (t);
什么可以是这个问题?有没有更好的办法?更喜欢使用词法转换
重要的是,上面的'string_convert'模板不只是方便忽略空格:如果还忽略尾随非空白,可能也预示无效值。 'trim'确实更健壮,或者你可以改变'string_convert' ala'char c; std :: stringstream ss(given); if(!(ss >> output)||(ss >> c))...'。 – 2011-04-08 05:44:16
如果你想要一个忽略尾随空格的转换函数,你应该这样做:'std :: stringstream(given); if(!(s >> output >> ws)|| s.get()!= EOF)throw ...' – 2011-04-08 09:41:00