float< - > std :: string转换替代?

时间:2011-09-25 21:00:14

标签: c++ string stl floating-point

除了atofstrtodlexical_caststringstream还是sprintf之外还有其他选择吗?

即:

  1. C ++方式(std::string代替char*
  2. 安全(无缓冲区溢出风险)
  3. 有效(如果无法转换,则返回NaN)
  4. 没有外部图书馆(独立)
  5. 我更喜欢this,这是一个简单的函数,已经过优化,而且还有点

    原因:

    • atofstrtod是C函数,他们在失败时没有返回NaN,我更喜欢std::string,所以我只想问是否有人已经写了一些包装器到我可以使用的std::string(如果你不介意的话)。
    • lexical_cast有提升依赖性
    • stringstream很慢
    • sprintf有缓冲区溢出风险及其C函数

3 个答案:

答案 0 :(得分:1)

我会看看提升精神

至少格式化程序的基准(即float - >字符串)始终是最高的* 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;
}

<子>

  
      
  • 升压/概念
  •   
  • 升压/配置
  •   
  • 升压/细节
  •   
  • 升压/异常
  •   
  • 升压/融合
  •   
  • 升压/迭代
  •   
  • 升压/数学
  •   
  • 升压/ MPL
  •   
  • 升压/任选的
  •   
  • 升压/预处理器
  •   
  • 升压/原
  •   
  • 升压/范围
  •   
  • 升压/正则表达式
  •   
  • 升压/精神
  •   
  • 升压/ typeof运算
  •   
  • 升压/ type_traits
  •   
  • 升压/效用
  •   
  • 升压/变体
  •   
     

aligned_storage.hpp,assert.hpp,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,交换.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

答案 1 :(得分:1)

如果你想从数字类型转换为std :: string,那么最新标准中有一个std::to_string函数。

不幸的是,我最近发现,在Visual Studio 2010中它有点受限,因为它只有三个可用的重载;长双,长长,无长对称。当尝试在模板中使用它们时,这会导致问题。

答案 2 :(得分:0)

fast format库应该能够进行您正在寻找的各种转换,至少对于写出浮点数。但是,它不处理float的解析。