Amir Saniyan
Amir Saniyan

Reputation: 13759

Which function should be use to converting string to long double?

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

strtod converts string to double, but which function should be use to converting string to long double?

Upvotes: 4

Views: 2350

Answers (4)

Steve Jessop
Steve Jessop

Reputation: 279305

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 as to exactly which formats each one accepts, so check the details first...

Upvotes: 15

Shahbaz
Shahbaz

Reputation: 47553

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

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

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272607

You've tagged your question as "C++", so I'm going to give you a C++ answer:

Why not just use streams?

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

Upvotes: 6

Matthieu M.
Matthieu M.

Reputation: 299969

In c++, I can only recommend boost::lexical_cast (or in general via the IOStreams).

In c ? no idea.

Upvotes: 1

Related Questions