-4

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

助けてください

4

3 に答える 3

2

構文:

#include <stdlib.h>
double atof( const char *str ); 

入力文字列は、指定された戻り値の型の数値として解釈できる一連の文字です。

関数は、数値の一部として認識できない最初の文字で入力文字列の読み取りを停止します。この文字は、文字列を終了するヌル文字にすることができます。

atof() 関数は、次の形式の文字列を想定しています。

     Read syntax diagramSkip visual syntax diagram
>>-+------------+--+-----+--+-digits--+---+--+--------+-+------->
       '-whitespace-'  +- + -+  |         '-.-'  '-digits-' |
                       '- – -'  '-.--digits-----------------'

したがって、問題は、文字列を受け入れるように設計されていない atof 関数にあり、文字を整数形式で格納しません。

これが役に立てば幸い.. :D

于 2013-08-14T05:15:55.303 に答える