Carolyn Drobak Carolyn Drobak - 10 months ago 76
C++ Question

Trouble with C++ Vector of Vectors

I am trying to read in a txt file line by line, where each line may have a different number of elements. I found vectors of vectors, but I can't figure out why mine is only writing to the first vector within the vector. All others are empty.

Here's the snippet of code reading in the data:

vector<vector<int>> all(numverts);
for (int i = 0; i <= (numverts - 1); i++) {
// reads a line of data
vector<int> edges;
int connect;
while (filein >> connect) {
all[i] = edges;

Answer Source

You can use getline and a stringstream. This way each line of the file is read separately, and then feed into the vector (via a stringstream).

vector<vector<int> > all(numverts);
for(int i = 0; i < numverts; i++)
    std::string line;
    std::getline(filein, line);
    std::stringstream lineStream(line);
    int connect;
    while(lineStream >> connect)