如何在C++中将字符串转换为double?我想要一个函数,当字符串不是数字时返回0.
请参阅C++ FAQ Lite 如何将std :: string转换为数字?
请参阅C++ Super-FAQ 如何将std :: string转换为数字?
请注意,根据您的要求,您无法将所有允许的零字符串表示与非数字字符串区分开来.
// the requested function #includedouble 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; }
最简单的方法是使用boost :: lexical_cast:
double value; try { value = boost::lexical_cast(my_string); } catch (boost::bad_lexical_cast const&) { value = 0; }
atof和strtod做你想要的,但非常原谅.如果你不想接受像"32asd"这样的字符串有效,你需要在这样的函数中包装strtod:
#includedouble strict_str2double(char* str) { char* endptr; double value = strtod(str, &endptr); if (*endptr) return 0; return value; }
如果它是一个c-string(以null为终结的char类型数组),你可以这样做:
#includechar str[] = "3.14159"; double num = atof(str);
如果它是C++字符串,只需使用c_str()方法:
double num = atof( cppstr.c_str() );
atof()会将字符串转换为double,失败时返回0.该功能记录在此处:http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html
#include#include using namespace std; int main() { cout << stod(" 99.999 ") << endl; }
输出:(99.999
为双精度,空格被自动剥离)
由于C ++ 11转换字符串浮点值(例如双)是可用的功能:
STOF -转换STR为float
STOD -转换STR为双
STOLD -转换STR为长双
我想要一个在字符串不是数字时返回0的函数。
您可以在stod
引发异常时添加try catch语句。