See C++ FAQ Lite How do I convert a std::string to a number?
See C++ Super-FAQ How do I convert a std::string to a number?
Please note that with your requirements you can't distinguish all the the allowed string representations of zero from the non numerical strings.
// the requested function
#include <sstream>
double string_to_double( const std::string& s )
{
std::istringstream i(s);
double x;
if (!(i >> x))
return 0;
return x;
}
// some tests
#include <cassert>
int main( int, char** )
{
// simple case:
assert( 0.5 == string_to_double( "0.5" ) );
// blank space:
assert( 0.5 == string_to_double( "0.5 " ) );
assert( 0.5 == string_to_double( " 0.5" ) );
// trailing non digit characters:
assert( 0.5 == string_to_double( "0.5a" ) );
// note that with your requirements you can't distinguish
// all the the allowed string representation of zero from
// the non numerical strings:
assert( 0 == string_to_double( "0" ) );
assert( 0 == string_to_double( "0." ) );
assert( 0 == string_to_double( "0.0" ) );
assert( 0 == string_to_double( "0.00" ) );
assert( 0 == string_to_double( "0.0e0" ) );
assert( 0 == string_to_double( "0.0e-0" ) );
assert( 0 == string_to_double( "0.0e+0" ) );
assert( 0 == string_to_double( "+0" ) );
assert( 0 == string_to_double( "+0." ) );
assert( 0 == string_to_double( "+0.0" ) );
assert( 0 == string_to_double( "+0.00" ) );
assert( 0 == string_to_double( "+0.0e0" ) );
assert( 0 == string_to_double( "+0.0e-0" ) );
assert( 0 == string_to_double( "+0.0e+0" ) );
assert( 0 == string_to_double( "-0" ) );
assert( 0 == string_to_double( "-0." ) );
assert( 0 == string_to_double( "-0.0" ) );
assert( 0 == string_to_double( "-0.00" ) );
assert( 0 == string_to_double( "-0.0e0" ) );
assert( 0 == string_to_double( "-0.0e-0" ) );
assert( 0 == string_to_double( "-0.0e+0" ) );
assert( 0 == string_to_double( "foobar" ) );
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…