如何在 C++ 中将字符串转换为双精度值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/392981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:06:26  来源:igfitidea点击:

How can I convert string to double in C++?

c++

提问by Alessandro Jacopson

How can I convert string to double in C++? I want a function that returns 0 when the string is not numerical.

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

回答by Alessandro Jacopson

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

请参阅 C++ FAQ Lite如何将 std::string 转换为数字?

See C++ Super-FAQ How do I convert a std::string to a number?

请参阅 C++ Super-FAQ如何将 std::string 转换为数字?

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

回答by Evgeny Lazin

Most simple way is to use boost::lexical_cast:

最简单的方法是使用boost::lexical_cast

double value;
try
{
    value = boost::lexical_cast<double>(my_string);
}
catch (boost::bad_lexical_cast const&)
{
    value = 0;
}

回答by jmucchiello

atof and strtod do what you want but are very forgiving. If you don't want to accept strings like "32asd" as valid you need to wrap strtod in a function such as this:

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

回答by Colin

If it is a c-string (null-terminated array of type char), you can do something like:

如果它是一个 c 字符串(字符类型的空终止数组),您可以执行以下操作:

#include <stdlib.h>
char str[] = "3.14159";
double num = atof(str);

If it is a C++ string, just use the c_str() method:

如果是C++字符串,只需使用c_str()方法:

double num = atof( cppstr.c_str() );

atof() will convert the string to a double, returning 0 on failure. The function is documented here: http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html

atof() 会将字符串转换为双精度值,失败时返回 0。该函数记录在此处:http: //www.cplusplus.com/reference/clibrary/cstdlib/atof.html

回答by Bad

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << stod("  99.999  ") << endl;
}

Output: 99.999(which is double, whitespace was automatically stripped)

输出:(99.999这是双倍,空格被自动剥离)

Since C++11 converting string to floating-point values (like double) is available with functions:
stof- convert str to a float
stod- convert str to a double
stold- convert str to a long double

由于 C++11 将字符串转换为浮点值(如 double)可用于以下函数:
stof- 将 str 转换为浮点数
stod- 将 str 转换为 double
stold- 将 str 转换为 long double

I want a function that returns 0 when the string is not numerical.

我想要一个当字符串不是数字时返回 0 的函数。

You can add try catch statement when stodthrows an exception.

您可以在stod抛出异常时添加 try catch 语句。

回答by martiert

Must say I agree with that the most elegant solution to this is using boost::lexical_cast. You can then catch the bad_lexical_cast that might occure, and do something when it fails, instead of getting 0.0 which atof gives.

必须说我同意最优雅的解决方案是使用 boost::lexical_cast。然后,您可以捕获可能发生的 bad_lexical_cast,并在失败时执行某些操作,而不是获得 atof 给出的 0.0。

#include <boost/lexical_cast.hpp>
#include <string>

int main()
{
    std::string str = "3.14";
    double strVal;
    try {
        strVal = boost::lexical_cast<double>(str);
    } catch(bad_lexical_cast&) {
        //Do your errormagic
    }
    return 0;
}

回答by hyperboreean

One of the most elegant solution to this problem is to use boost::lexical_cast as @Evgeny Lazin mentioned.

这个问题最优雅的解决方案之一是使用 boost::lexical_cast 正如@Evgeny Lazin 提到的那样。

回答by Kyle Cronin

I think atofis exactly what you want. This function parses a string and converts it into a double. If the string does not start with a number (non-numerical) a 0.0 is returned.

我认为atof正是您想要的。此函数解析一个字符串并将其转换为双精度值。如果字符串不以数字(非数字)开头,则返回 0.0。

However, it does try to parse as much of the string as it can. In other words, the string "3abc" would be interpreted as 3.0. If you want a function that will return 0.0 in these cases, you will need to write a small wrapper yourself.

但是,它确实尝试尽可能多地解析字符串。换句话说,字符串“3abc”将被解释为 3.0。如果您想要一个在这些情况下返回 0.0 的函数,您将需要自己编写一个小包装器。

Also, this function works with the C-style string of a null terminated array of characters. If you're using a string object, it will need to be converted to a char* before you use this function.

此外,此函数可与空终止字符数组的 C 样式字符串一起使用。如果您使用的是字符串对象,则需要在使用此函数之前将其转换为 char*。

回答by Ron Savage

There is not a single function that will do that, because 0 is a valid number and you need to be able to catch when the string is not a valid number.

没有一个函数可以做到这一点,因为 0 是一个有效数字,当字符串不是一个有效数字时,您需要能够捕捉到。

You will need to check the string first (probably with a regular expression) to see if it contains only numbers and numerical punctuation. You can then decide to return 0 if that is what your application needs or convert it to a double.

您需要首先检查字符串(可能使用正则表达式)以查看它是否仅包含数字和数字标点符号。如果这是您的应用程序所需要的,您可以决定返回 0 或将其转换为双精度值。

After looking up atof()and strtod()I should rephrase my statement to "there shouldn't be" instead of "there is not" ... hehe

在查找atof()strtod() 之后,我应该将我的陈述改写为“不应该有”而不是“没有”......呵呵