我看到很多将字符串转换为数字的选项,其中一些实际上推荐使用标准C函数,例如atoi
和atof
。
我没有看到有人建议以下选项,它完全依赖于C ++ STL:
int Str2Num(const string& str) // can be called with a 'char*' argument as well
{
int num;
istringstream(str)>>num;
return num;
}
更普遍而言:
template <typename type>
type Str2Num(const string& str) // can be called with a 'char*' argument as well
{
type num;
istringstream(str)>>num;
return num;
}
以上实现方式有哪些缺点?
是否有更简单/更清晰的方法来实现此转换?
boost::lexical_cast
: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast.html - Messa