is there any alternative to atof
, strtod
, lexical_cast
, stringstream
or sprintf
?
that is:
- fast
- C++ way (
std::string
instead ofchar*
) - safe (no buffer overrun risk)
- valid (return NaN if 开发者_StackOverflowconversion couldn't be made)
- no external library (independent)
I prefer more like this , a simple function, optimized, and to the point
reason :
atof
andstrtod
is C function and they are not returningNaN
upon failure, I prefer working onstd::string
, so I just asking if anyone already writing some wrapper tostd::string
that I can use (if you don't mind).lexical_cast
has boost dependencystringstream
is slowsprintf
has buffer overflow risk and its C function
I'd look at Boost Spirit
- http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/qi/reference/numeric/real.html
At least the benchmarks of the formatters (that is float -> string) consistently turn out as top-of-the-bill*1*
Also the exact input format specification and semantics when parsing can be configured very nicely using a policy class.
Here is my absolute min-dependency use of qi::any_real_parser<> and the list of dependendencies it touches:
#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;
}
- boost/concept
- boost/config
- boost/detail
- boost/exception
- boost/fusion
- boost/iterator
- boost/math
- boost/mpl
- boost/optional
- boost/preprocessor
- boost/proto
- boost/range
- boost/regex
- boost/spirit
- boost/typeof
- boost/type_traits
- boost/utility
- boost/variant
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,swap.hpp,throw_exception.hpp,type.hpp,utility.hpp,variant.hpp,version.hpp
1 e.g. http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/karma/performance_measurements/numeric_performance/double_performance.html
If you want to convert from numerical types to std::string there's a std::to_string
function available in the latest standard.
Unfortunately as I've found out recently, in Visual Studio 2010 it is somewhat limited because there are only three overloads available for it; long double, long long, and unsigned long long. This causes issues when trying to use them from within templates.
The fast format library should be able to do the kinds of transformations you're looking for, at least for writing a float out. It does not handle parsing of a float, however.
精彩评论