interaction of size_type and substr()

I am trying to teach myself c++. I've been to the C++ definitions but I'm not very good at understanding the definitions.

My code works and I think I can do what I want, but I'm struggling with understanding the code I copied from an example.

What is "float earth = std::stof(orbits.substr(sz));" doing? It returns a number, but I don't understand how substring knows to pull the second number of the string. And how would I get another substring to pull the third number that I added (purposely not the same length as the first two).

Is size_type identifying the length of the first parsed string?
If yes, somehow does the "substr(sz)" know to begin after the first number pulled?


1
2
3
4
5
6
7
std::string orbits("686.97 365.24 456.9");
std::string::size_type sz;    

float mars = std::stof(orbits, &sz);
float earth = std::stof(orbits.substr(sz));
float test = std::stof(orbits.substr(0, 2));
float planet = std::stof(orbits.substr(1, 7));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>

int main()
{
    const std::string str = "686.97 365.24 456.9" ;

    {
        std::size_t pos ;

        std::cout << std::quoted(str) << '\n' ;

        // the the number of characters parsed is stored in pos
        const float first = std::stof( str, &pos ) ;
        std::cout << "first == " << first << "  ("
                  << pos << " characters were parsed)\n\n" ;

        const std::string residue = str.substr(pos) ; // substring from postion 'pos' onwards
        std::cout << "residue: " << std::quoted(residue) << '\n' ;
        const float second = std::stof( residue, &pos ) ;
        std::cout << "second == " << second << "  ("
                  << pos << " characters were parsed)\n\n" ;

        const std::string residue2 = residue.substr(pos) ;
        std::cout << "residue2: " << std::quoted(residue2) << '\n' ;
        const float third = std::stof(residue2) ;
        std::cout << "third == " << third << '\n' ;
    }

    {
        std::cout << "\n--------\nusing stringstream to parse the string\n\n" ;
        std::istringstream stm(str) ;
        float first, second, third ;
        if( stm >> first >> second >> third ) std::cout << first << ' ' << second << ' ' << third << '\n' ;
    }

}

http://coliru.stacked-crooked.com/a/b0447af408e20297
thank you. i get it now. very helpful
for some reason "quoted" gave me errors though.
> for some reason "quoted" gave me errors though

std::quoted came with C++14.

With the GNU compiler, compile with -std=c++14
Topic archived. No new replies allowed.