Can't understand the meaning of some code using stod()

I am not understanding the meaning of the following 2 lines. What does it tell the program to do?

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


Here is the full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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
stod is used to "read" a double from a string. In this case the string orbits contains several doubles, so the first call to stod returns the first double, and then the location at where it stopped is stored in sz. After that stod is called again, but on the substring that starts at sz, in other words on the last double in the string. In other words, the first call to stod returns "365.24", the second call gets the substring that starts after sz, namely "29.53".
ok...then if i want to rear three double from a string?? then what will be the code?

1
2
3
4
5
    string orbits = "365.24 29.53";


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


Why not just do
1
2
double earth = 365.24;
double moon = 29.53;
?

Also these may help you with stod (string to double) http://www.cplusplus.com/reference/string/stod/?kw=stod
http://en.cppreference.com/w/cpp/string/basic_string/stof
To read three doubles would be

1
2
3
4
5
6
7
string orbits = "365.24 29.53 13.37";

string::size_type sz;     // alias of size_t

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


although I haven't tried it out.
Thnak you all..its clear now.
Topic archived. No new replies allowed.