Suppose there is a string ( string , not char ) = "1234.55" . How to convert it into a full real number?
|
3 answers
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
atofandsscanfnot counted - they give rise to undefined overflow behavior. - AnT - @AnT
sscanfshould issue aninfif overflowed, if I remember correctly, of course. We have a floating point in the condition. I won't say aboutatof, yt remember exactly ... but I think that inside it is the same as insscanf:) - Harry - Both
sscanfandatofundefined overflow behavior. In this sense, they really have the same inside.infguaranteed exactly and onlystrtod.sscanfhas one more subtlety - its behavior should be equivalent tofscanf. Andfscanfinfscanfqueue must be implemented so that it returns no more than one character back to the stream. Atstrtodthere is no such restriction. Therefore, the character sequences taken bysscanfandstrtodmay 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"); |
atoi, for which you have to kick ass. - AnT