Can't convert 3 doubles from a string using stod()

I've found the following code as reference of stod() function. Here 2 doubles are converted from a string using the following code.
1
2
double earth = stod (orbits,&sz);
double moon = stod (orbits.substr(sz));

If I want to convert 3 doubles from a string then how to do it this way?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string orbits = "365.24 29.53";

    string::size_type sz;     // alias of size_t

    double earth = stod (orbits,&sz);
    double moon = stod (orbits.substr(sz));

    cout << "The moon completes " << (earth/moon) << " orbits per Earth year."<<endl;

    return 0;
}
Last edited on
You can try this
1
2
3
4
5
6
7
8
string str = "1.02 1.4 2.7";
size_t size = 0;
double x = stod(str, &size);
string sub1 = str.substr(size);
double y = stod(sub1, &size);
string sub2 = sub1.substr(size);
double z = stod(sub2);
cout<<x<<endl<<y<<endl<<z;

I just modified your code a little bit :D
Last edited on
:D Thank you...it works perfectly. But I don't understand how it is working.

Would you please explain the code for me?
Last edited on
stod() function returns the first double number contained in str, and the variable size will be assigned the index of the next character after that number in str
After this code double x = stod(str, &size); size == 4, the index of ' ' (space) right after the number 1.02 in str
Topic archived. No new replies allowed.