string object conversion to double

Hi,

Is there a way to convert a string object directly to a double instead of this:
1
2
string str = "3.14159265";
double pi = atof( str.c_str() );


Hannes
How more direct can you get than one instruction?
Not sure what do you mean by "directly". But here is an alternate approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;

int main()
{
string sd = "3.14159265";
double d;
istringstream iss(sd);
iss >> d;
cout << setprecision(9) << d << endl;
}
Last edited on
You can overload =. That'll be quite short after you declare and define the overloaded operator (which takes some space, mind you), although what you posted is one of the shortest if not the shortest way of converting a string to a double.

-Albatross
Topic archived. No new replies allowed.