String to Long Double

Ok everyone:
I am having Mucho trouble trying to convert a string to a long double.  For instance:

std::string
  str1;

double
  d1 = 2532123.443;

now how would I convert str1 to d1?

Thanks a lot

Ernie
fastawdtsiAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Tommy BraasConnect With a Mentor Commented:
Use the function strod(...) defined in stdlib.h. Prototype follows;

double strod(const char *s, char **end_ptr)

Converts the string 's' to a double and returns it. The 'end_ptr' will point to the first element in the string PAST the number.

double myDouble = strod("12341.523452", NULL);

The NULL passed in just means that no pointer will be returned.

If you would like, I could recommend some good books on C and C++.
0
 
pku_hawkCommented:
try this

#include <iostream>
#include <sstream>
#include <string>
 
 double convertFromString(const std::string& s)
 {
   std::istringstream i(s);
   double x;
   if (i >> x)
     return x;
   // some sort of error handling goes here...
   return 0.0;
 }

int main()
{
  double d;
  std::string s="3.14";
  std::cout << "s= " << convertFromString(s) << " when converted to a double"  << std::endl;
}
0
 
DanRollinsCommented:
extending orangehead911's comment to make it apply more directly to your question:
 
   double myDouble = strod( str1.c_str(), NULL );

-- Dan
0
 
fastawdtsiAuthor Commented:
Thanks a lot...what would be some good book for C/C++.  I just bought "The Complete Reference to C++, 4th edition" the other day...

Ernie
0
 
Tommy BraasCommented:
I swear by, for C, " A Book On C", ISBN 0-201-18399-4.
For C++, I think this book has the most value in terms of coverage; "C++ Primer" by Stan Lippman, ISBN 0-201-82470-1. Another book to keep handy would be one on the STL (Standard Template Library). I find the "STL Tutorial and Reference Guide, Second Edition", ISBN 0-201-37923-6. I use Bookpool to buy my books, cheapest place I've found!
0
All Courses

From novice to tech pro — start learning today.