浮点<-> std::字符串转换替代方案?
float <-> std::string conversion alternative?
是否有atof
, strtod
, lexical_cast
, stringstream
或sprintf
的替代品?
:
- 快速
- c++方式(
std::string
代替char*
) - 安全(无缓冲区溢出风险)
- 有效(如果无法进行转换则返回NaN)
- 没有外部库(独立)
我更喜欢这样的,一个简单的函数,优化,和点
原因:
-
atof
和strtod
是C函数,它们在失败时不返回NaN
,我更喜欢在std::string
上工作,所以我只是问是否有人已经编写了一些包装器到std::string
,我可以使用(如果你不介意)。 -
lexical_cast
有boost依赖 -
stringstream
是慢的 -
sprintf
存在缓冲区溢出风险及其C函数
我会看看Boost Spirit
- http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/qi/reference/numeric/real.html
至少格式化程序的基准测试(即float -> string)始终是顶级的*1*
解析时的确切输入格式规范和语义也可以使用策略类很好地配置。
下面是我对qi::any_real_parser<>的绝对最小依赖的使用,以及它所涉及的依赖列表:
#include <boost/spirit/include/qi_real.hpp>
namespace qi = boost::spirit::qi;
int main()
{
const char input[] = "3.1415926";
const char *f(input);
const char *l(f+strlen(input));
qi::any_real_parser<double> x;
double parsed;
x.parse(f, l, qi::unused, qi::unused, parsed);
return 0;
}
<子>
<
- 增加/概念/gh>
- 增加/配置
- 增加/细节
<- 增加/异常/gh>
- 增加/融合
- 增加/迭代器
- 增加/数学
- 增加/mpl
- 增加/可选
- 增加/预处理器
- 增加/原型
- 增加/范围
- 增加/regex
<- 增加/精神/gh>
- 增加/typeof
- boost/type_traits
- 增加/效用
- 增加/变异
aligned_storage.hpp, assert .、blank_fwd.hpp blank.hpp, call_traits.hpp, checked_delete.hpp, concept_check.hpp, config.hpp, cstdint.hpp, current_function.hpp, foreach_fwd.hpp, foreach.hpp, get_pointer.hpp, implicit_cast.hpp, iterator.hpp, limits.hpp, math_fwd.hpp, next_prior.hpp, noncopyable.hpp, none.hpp, none_t.hpp, optional.hpp, ref.hpp, static_assert.hpp, swap.hpp, throw_exception.hpp, type.hpp, utility.hpp, variant.hpp, version.hpp
子>
1例如http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/karma/performance_measurements/numeric_performance/double_performance.html
如果您想从数字类型转换为std::string,在最新的标准中有一个std::to_string
函数可用。
不幸的是,正如我最近发现的,在Visual Studio 2010中,它有些有限,因为只有三个重载可用;长双,长长,和无符号长长。当试图在模板中使用它们时,这会导致问题。
快速格式库应该能够完成您正在寻找的各种转换,至少对于编写float out来说是这样。但是,它不处理浮点数的解析。
- 如何将这种递归解决方案转换为分而治之?
- 将多个非原始递归调用转换为迭代解决方案
- 我在 TSP 的C++解决方案中遇到转换错误
- 如何在C VS2012中转换或创建.NET V3.5解决方案(特别是工具集)
- 数据转换解决方案
- 将递归解决方案转换为迭代解决方案
- 如何将递归解决方案转换为自下而上或自上而下的解决方案
- 将一维矩阵数组转换为主一维矩阵的有趣算法挑战,需要有效的解决方案
- C++ - 标准::地图 不需要强制转换的替代方案
- 如何将递归解决方案转换为迭代解决方案
- 将int转换为void*会丢失精度,在需要的情况下解决方案是什么
- 浮点<-> std::字符串转换替代方案?
- 将此自定义回合转换为数学更友好的解决方案
- 将'makefile.vc'转换为'.sln'解决方案文件
- 通用转换运算符模板和移动语义:有通用的解决方案吗
- c++ CLI - C++/CLI:为什么在此方案中没有托管>非托管转换?
- C++需要从常量字符串转换的解决方案
- 转换vc++解决方案和项目文件从32位到64位
- 如何在c++11中将迭代器转换为字符串?boost解决方案也可以
- Visual Studio 2010 2005解决方案的转换(c++项目)失去了项目依赖关系