当我使用以下代码将字符串转换为浮点数时,它工作正常。但是下一个代码给出了错误。请告诉我为什么会这样?字符串是一个字符数组,只是我读到的。
代码1(工作)
#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;
}
代码 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;
}
错误:
error: cannot convert std::string to const char* for argument 1 to double atof(const char*)
请帮忙