I’m trying to load each line from a file in to a 2D string vector, but I keep getting a segmentation fault. Can someone show me what’s going wrong? Thanks in advance.
Printing lcount was just a way to verify that all lines were loaded (190k lines).
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int loadVector(ifstream& fh, vector< vector<string> >& v);
int main(int argc, char *argv[])
{
ifstream fh1(argv[1]);
ifstream fh2(argv[2]);
vector< vector<string> > v1;
vector< vector<string> > v2;
int v1_lines = loadVector(fh1, v1);
int v2_lines = loadVector(fh2, v2);
cout << "v1: " << v1_lines << "\n";
cout << "v2: " << v2_lines << "\n";
}
int loadVector(ifstream& fh, vector< vector<string> >& v){
int lcount = 0;
while (fh.good() && fh){
string line = "";
getline(fh, line);
v[lcount].push_back(line);
++lcount;
}
fh.close();
return lcount+1;
}
The line:
will seg fault because you’re accessing v[lcount] before putting any vector elements into vector v. Do v.push_back(vector()) to give that element a vector, and then fill in the inner vector with the line above.
Remember, it’s a vector of vectors. The first vector contains vectors, but if it doesn’t contain any yet then accessing its [0]’th element is undefined behavior because you’re accessing uninitialized memory. The [0]th element only exists once you’ve pushed an element (your 2nd dimension vector) into it the first time.
PS: I don’t think you need a 2-d vector here, you can just do a vector of strings from the look of it.