字符串常用-----atof()函数,atoi()函数

头文件:#include <stdlib.h>

函数 atof() 用于将字符串转换为双精度浮点数(double),其原型为:
double atof (const char* str);

atof() 的名字来源于 ascii to floating point numbers 的缩写,它会扫描参数str字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过 isspace() 函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('')才结束转换,并将结果返回。参数str 字符串可包含正负号、小数点或E(e)来表示指数部分,如123. 456 或123e-2。

【返回值】返回转换后的浮点数;如果字符串 str 不能被转换为 double,那么返回 0.0。

下面做了个测试:

#include<cstdlib>
#include<iostream>
using namespace std;
int main(){
    ios::sync_with_stdio(false);
    
    char str[100]  = "       0123.123+1";
    double num = atof(str);
    int n = atoi(str);
    cout<<num<<endl;
    cout<<n<<endl;
    return 0;
}

输出:

123.123
123

原文地址:https://www.cnblogs.com/slothrbk/p/6809594.html