次のコードを使用して文字列を浮動小数点数に変換すると、正常に動作します。しかし、次のコードでエラーが発生します。なぜこれが起こっているのか教えてください。文字列は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;
}
コード 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*)
助けてください