Suppose there is a string ( string , not char ) = "1234.55" . How to convert it into a full real number?

3 answers 3

I recommend using the function from the standard std , which appeared in c ++ 11:

 double stod (const string& str, size_t* idx = 0); 

Detailed information on it can be found here .

    It is even interesting to estimate the number of ways ...

     string s; double d; 1. d = stod(s); 2. d = atof(s.c_str()); 3. sscanf(s.c_str(),"%lf",&d); 4. strtod(s.c_str(),0); 5. istringstream(s) >> d; 

    Who is bigger? :)

    • It depends on what is considered a "way". If the method does not provide the ability to control errors (overflow, for example), then it is very difficult to consider it the “way”. Those. that atof and sscanf not counted - they give rise to undefined overflow behavior. - AnT
    • @AnT sscanf should issue an inf if overflowed, if I remember correctly, of course. We have a floating point in the condition. I won't say about atof , yt remember exactly ... but I think that inside it is the same as in sscanf :) - Harry
    • Both sscanf and atof undefined overflow behavior. In this sense, they really have the same inside. inf guaranteed exactly and only strtod . sscanf has one more subtlety - its behavior should be equivalent to fscanf . And fscanf in fscanf queue must be implemented so that it returns no more than one character back to the stream. At strtod there is no such restriction. Therefore, the character sequences taken by sscanf and strtod may differ. (In this case, however, the latter is most likely irrelevant.) - AnT
    • @AnT Can I have some kind of link? just searched - I didn't find anything either way ... - Harry
    • Undefined behavior when overflowing: fscanf "7.21.6.2/9 [...] sequence. " "7.21.6.2/10 [...] [...] If this object does not have This behavior is undefined. ". - AnT

    Let us suppose:

     float i = boost::lexical_cast<float>("123.321");