📜  C++ atof()

📅  最后修改于: 2020-09-25 08:46:31             🧑  作者: Mango

C++中的atof() 函数将字符串的内容解释为浮点数,并以双精度形式返回其值。

atof()原型

double atof(const char* str);

它在头文件中定义。

atof()参数

atof()返回值

atof() 函数返回:

如果转换后的值超出范围,则将导致未定义的行为。

示例1:atof() 函数如何工作?

#include 
#include 

using namespace std;

int main()
{
    char numberString[] = "-32.40"; 
    double numberInDouble;
    cout << "Number in  String = " << numberString << endl;

    numberInDouble = atof(numberString);
    cout << "Number in Double = " << numberInDouble;
    
    return 0;
}

运行该程序时,输出为:

Number in  String = -32.40
Number in Double = -32.4

atof() 函数的有效浮点值包含一个可选的+或-号,后跟以下一组值:

示例2:atof()如何使用指数和十六进制?

#include 
#include 
using namespace std;

int main()
{

    cout << "-44.01e-3" << " to Double = " << atof("-44.01e-0") << endl;
    cout << "-44.01e-3" << " to Double = " << atof("-44.01e-3") << endl;
    
    cout << "0xf1bc" << " to Double = " << atof("0xf1bc") << endl;
    cout << "0xf1bc.51" << " to Double = " << atof("0xf1bc.51") << endl;
    
    return 0;
}

运行该程序时,输出为:

-44.01e-3 to Double = -44.01
-44.01e-3 to Double = -0.04401
0xf1bc to Double = 61884
0xf1bc.51 to Double = 61884.3

例3:INFINITY和NaN的atof案例

#include 
#include 
using namespace std;

int main()
{
    cout << "INFINITY" << " to Double = " << atof("INFINITY") << endl;
    cout << "Inf" << " to Double = " << atof("Inf") << endl;

    cout << "Nan" << " to Double = " << atof("Nan") << endl;
    cout << "NAN" << " to Double = " << atof("NAN") << endl;
    
    return 0;
}

运行该程序时,输出为:

INFINITY to Double = inf
Inf to Double = inf
Nan to Double = nan
NAN to Double = nan

通常,atof() 函数的有效浮点参数具有以下形式:

[whitespace] [- | +] [digits] [.digits] [ {e | E }[- | +]digits]

直到主非空白字符被找到ATOF() 函数将忽略所有的前导空白字符 。

然后,从该字符开始,它需要尽可能多的字符 ,以形成有效的浮点表示形式并将其转换为浮点值。最后一个有效字符之后的字符串剩余部分将被忽略,并且对结果没有任何影响。

示例4:带有空白和结尾字符的 atof() 函数

#include 
#include 
using namespace std;

int main()
{
    cout << "25.5" << " to Double = " << atof("  25.5") << endl;
    cout << "25.5    " << " to Double = " << atof("  25.5   ") << endl;
    cout << "25.5abcd" << " to Double = " << atof("25.5abcd") << endl;

    // Returns 0 because of invalid conversion
    cout << "abcd25.5" << " to Double = " << atof("abcd25.5") << endl;

    // Rules for whitespace and trailing character also apply for infinity and Nan
    cout << "INFINITYabcd" << " to Double = " << atof("INFINITYabcd") << endl;
    cout << "INFINITY" << " to Double = " << atof("  INFINITY") << endl;
    cout << "Nanlll" << " to Double = " << atof("Nanlll") << endl;

    return 0;
}

运行该程序时,输出为:

25.5 to Double = 25.5
25.5     to Double = 25.5
25.5abcd to Double = 25.5
abcd25.5 to Double = 0
INFINITYabcd to Double = inf
INFINITY to Double = inf
Nanlll to Double = nan