styko
styko

Reputation: 701

C++ simplest way of loading "irregular" data from file

I have a data file (representing an adjacency lists) that I would like to load as a std::vector< std::list<int> >.

1 2 4
0 2
0 1

0

What is the cleanest way to do that in C++ / C++11?


Here is a crappy try, that doesn't work for blank lines…

vector< list<int> > data;
ifstream file("data.dat");
char foo;

while(file >> foo){
    file.unget();
    list<int> mylist;
    while( file.get() != '\n'){
        file.unget();
        int n;
        file >> n;
        mylist.push_back(n);
        cout << n;
    }
    data.push_back(mylist);
}

file.close();

Upvotes: 0

Views: 76

Answers (2)

Baum mit Augen
Baum mit Augen

Reputation: 50053

Just read line by line and parse that into lists:

for (std::string line; std::getline(file, line);) {
    std::istringstream str(line);
    data.emplace_back(std::istream_iterator<int>(str), std::istream_iterator<int>{});
}

Upvotes: 3

Russell Greene
Russell Greene

Reputation: 2271

Here's an idea: use getline:

std::string line
std::getline(file, line);

Then you could put this into a stringstream

std::stringstream s;
s.str(line);

Then insert them into the list

std::list<int>& list = data[lineNumber];
int num = 0;
while (s >> num)
    list.emplace_back(num);

Upvotes: 0

Related Questions