浮点<-> std::字符串转换替代方案?

float <-> std::string conversion alternative?

本文关键字:方案 转换 std lt gt 浮点 字符串      更新时间:2023-10-16

是否有atof, strtod, lexical_cast, stringstreamsprintf的替代品?

:

    快速
  1. c++方式(std::string代替char*)
  2. 安全(无缓冲区溢出风险)
  3. 有效(如果无法进行转换则返回NaN)
  4. 没有外部库(独立)

我更喜欢这样的,一个简单的函数,优化,和点

原因:

  • atofstrtod是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来说是这样。但是,它不处理浮点数的解析。