gpt4 book ai didi

c++ - 如何在 C++ 中将字符串转换为 double 值?

转载 作者:IT老高 更新时间:2023-10-28 12:35:03 27 4
gpt4 key购买 nike

如何在 C++ 中将字符串转换为 double 值?我想要一个在字符串不是数字时返回 0 的函数。

最佳答案

参见 C++ FAQ Lite How do I convert a std::string to a number?

请参阅 C++ super 常见问题解答 How do I convert a std::string to a number?

请注意,根据您的要求,您无法区分所有允许的零字符串表示形式和非数字字符串。

 // 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;
}

关于c++ - 如何在 C++ 中将字符串转换为 double 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/392981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com