慕少森
请注意,根据您的要求,您无法将所有允许的零字符串表示形式与非数字字符串区分开。 // the requested function #include double string_to_double( const std::string& s ) { std::istringstream i(s); double x; if (!(i >> x)) return 0; return x; } // some tests #include 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; }