这会因额外的空格而导致问题:
std::string t("3.14 ");
double d = boost::lexical_cast<double> (t);
Run Code Online (Sandbox Code Playgroud)
所以,我写了这个
template<typename T>
T string_convert(const std::string& given)
{
T output;
std::stringstream(given) >> output;
return output;
}
double d = string_convert<double> (t);
Run Code Online (Sandbox Code Playgroud)
这会有什么问题?有没有更好的办法?更喜欢使用词法演员
请注意,您的代码并不总是正确的.string_convert<double>("a")例如,如果您这样做,则读取将失败并且您将返回output未初始化,从而导致未定义的行为.
你可以这样做:
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,上述代码和Boost之间的唯一区别是Boost还会检查以确保流中没有任何内容.但是,你应该做的只是先修剪你的字符串:
#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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2172 次 |
| 最近记录: |