Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 919
Amir Saniyan Avatar asked Nov 28 '22 17:11

Amir Saniyan


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

like image 190
Steve Jessop Avatar answered Dec 01 '22 06:12

Steve Jessop


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;
like image 20
Oliver Charlesworth Avatar answered Dec 01 '22 06:12

Oliver Charlesworth