Which function should be used to convert a string to a long double?

Note that in general, double is different from long double .

strtod converts the string to double , but which function should be used to convert the string to long double?

+4
source share
4 answers

In C ++ 03, use boost::lexical_cast or:

 std::stringstream ss(the_string); long double ld; if (ss >> ld) { // it worked } 

In C99, use strtold .

In C89, use sscanf with %Lg .

In C ++ 11, use stold .

There may be subtle differences in exactly which formats each accepts, so check the details first ...

+14
source

You marked your question as "C ++", so I will give you a C ++ answer:

Why not just use streams?

 std::stringstream ss(myString); long double x; ss >> x; 
+6
source

In C ++, I can only recommend boost::lexical_cast (or generally through IOStreams).

In c? I do not know.

+1
source

You can use istream to read a long double from a string. See here http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/

If you like the scanf family of functions, read with %Lf

+1
source

All Articles