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