带字符串和字符数组的不同输出

Jig*_*asa -4 c++

当我使用以下代码将字符串转换为浮点数时,它工作正常.但是下一个代码会给出错误.请告诉我为什么会这样?String是一个char数组,只是我读过的.

Code1(工作)

#include<iostream>
#include<stdlib.h>


using namespace std;

int main()
{
    char str[]="301.23";
    float f=atof(str);
    cout<<sizeof(str)<<" is size with contents "<<str<<endl;
    cout<<sizeof(f)<<" is size with contents "<<f<<endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码2(不工作)

#include<stdlib.h>
#include<string>
#include<iostream>


using namespace std;

int main()
{
    string str="301.23";
    float f=atof(str);
    cout<<sizeof(str)<<" is size with contents "<<str<<endl;
    cout<<sizeof(f)<<" is size with contents "<<f<<endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

 error: cannot convert std::string to const char* for argument 1 to double atof(const char*)
Run Code Online (Sandbox Code Playgroud)

请帮忙

tam*_*ato 7

std::string不是char数组.
str.c_str()得到const char*,你应该罚款