Breaking apart a string and storing sub-strings

I'm looking to separate a string containing numbers separated by one space, ie: "1 14 22 6 7". After splitting them up I wanted to store them some how so I could manipulate each sub-string individually and run through them with a loop of some kind, probably for. I've tried using istringstream code snippets from online but don't understand the code enough to store them in something like a string array. I've also tried using fixed character counts but that doesn't help because these values will be changing. Thanks in advance.

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

using namespace std;

int main()
{
    string s("1 14 22 6 7");
    istringstream iss(s);

    do
    {
        string sub;
        iss >> sub;
        cout << sub << endl;
    } while (iss);

}

If they are numbers, why store them as strings? You probably want something like this:
1
2
3
4
5
6
7
8
std::vector<int> numbers;

std::istringstream iss {"1 14 22 6 7"};
int x;
while(iss >> x) //it is good practice to loop on the input operation
{
    numbers.push_back(x);
}
Or, if you do actually want them as strings, the code is not so different:

1
2
3
4
5
6
    std::vector<std::string> tokens;
    std::istringstream iss {"1 14 22 6 7"};

    std::string token ;
    while (iss >> token)
        tokens.push_back(token); 


which may lead to the conclusion that a more generalized template version might be a good idea:

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
// http://ideone.com/VamfzN
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

template <typename parsed_type>
std::vector<parsed_type> split(const std::string& text)
{
    std::istringstream iss(text);
    std::vector<parsed_type> elements;
    parsed_type element;

    while (iss >> element)
        elements.push_back(element);

    return elements;
}

template <typename container_type>
void print_container(std::ostream& os, const container_type& c)
{
    std::cout << '{';
    for (auto & item : c)
        std::cout << ' ' << item;
    std::cout << " }\n";
}

int main()
{
    std::string s("1 14 22 6 7");
    std::string words("alpha bravo charlie delta echo foxtrot golf");

    print_container(std::cout, split<int>(s));
    print_container(std::cout, split<std::string>(words));
}


See also: http://stackoverflow.com/questions/236129/split-a-string-in-c for a more in-depth look at splitting a string in C++.
Topic archived. No new replies allowed.