2

Anyone know how to convert a string to long double? For example lets say we have

string S = "3.236568949" 

I want to take what inside the string and convert it to a long double variable x.

Note: In c++11 their exist stold function do so but I'm using c++98 not c++11. Also I don't need to cout the string with certain precision because I know setprecision function already but what I want is just to convert to long double. In other wards,I need x to equal the exact number inside the string and not an approximated version of the number. Finally I want to tell you that my string contains a valid number.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
user288086
  • 33
  • 2
  • 6

3 Answers3

0

you can use the C function :

#include <stdlib.h>
int main(){
   char* convertme="3.236568949";
   double converted=atof(convertme);
   return 0;
}
GhaziBenDahmane
  • 548
  • 3
  • 15
0

You can use a std::stringstream to convert the string into a long double. The std::stringstream acts just like cin but instead of getting the input from the user you load it into the stream with a std::string. That looks like

std::string data = "3.236568949"
std::stringstream ss(data);
long double ld;
ss >> ld;

Do note that when dealing with floating point numbers you are going to have to deal with imprecision. For more on this see Is floating point math broken?

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • your code wokrs very well , can i select certain percision for ld ? – user288086 May 05 '17 at 17:25
  • @user288086 You cannot set the precision of the output but you can specify precision for things you input into the `stringstream`. – NathanOliver May 05 '17 at 17:27
  • @user288086 Just like you would using `cout`. – NathanOliver May 05 '17 at 17:37
  • tell me how please. – user288086 May 05 '17 at 17:43
  • @user288086 Well, you could extract a substring from the original string with only the desired figures or do something like [this](https://ideone.com/9w8srR), but given the nature of floating point representation (please, read the Q&A linked by NathanOliver and the mentioned [doc](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)) it seems quite an exercise in futility. – Bob__ May 05 '17 at 18:53
-1

You can use strtold() function from C99:

long double d = strtold( str.c_str(), nullptr );

to convert std::string to long double. Though floating point representation is approximate so nobody would guarantee that value after conversion is exactly the same is in your string.

Slava
  • 43,454
  • 1
  • 47
  • 90