I am having trouble "undoing" this method, that dumps essentially a matrix of numbers of variable size into a text file:
void vectorToFile(char *name, vector<vector<double>>* a){
FILE* fp = fopen(name, "w");
for(int i=0;i<a->size();i++){
for(int j=0;j<a->at(i).size();j++){
fprintf(fp, "%f ", a->at(i).at(j));
}
fprintf(fp, "\n");
}
fclose(fp);
}
I am having trouble implementing the reverse:
vector<vector<double>> fileToVector(char *name){ ??? }
I am guaranteed that the numbers in the file form a "rectangle", i.e. the sizes of inner vectors are all equal, but I don't know how to figure out the number of entries per row, and the number of columns.
Can anyone point me in the right direction? Every example I found so far implements something much easier, with hardcoded size, or sizes given in first row (which I cannot afford to do unfortunately)
It would be easier if you used C++ I/O instead of C I/O. I'd suggest using
ifstream
to read in the file and usegetline()
to read each line. Each line is then the numbers that are supposed to go in avector
. Probably the easiest way to parse thestring
would be to usestringstream
. You can then parse eachdouble
out andpush_back()
it onto thevector
, so you won't have to care about the size of thevectors
. I'd also suggest usingstd::string
instead ofchar*
wherever you can (though for file names, you generally end up having to usec_str()
on the them anyway since the file I/O stuff always seems to takeconst char*
instead ofstd::string
).You can read lines, split using the separator you have, then parse to numbers. You can use
getline
to read lines as strings and you won't need to know the exact number.Is there any particular reason to use the vector > instead of using just double** and using new double[] to allocate the array and each sub-element? My guess is that the array can be dynamically resized at runtime, but if the array is allocated only once, using double** is bound to be much more efficient than iterating over a vector.
In any case, the solution to your problem is to dump the bounds of the array up-front in the file and read it back...
I'm new at C++ so I'm not sure if this is a good approach or not, but I would open the file, read in the input line by line, parsing each line as I read it. Here's some example code (untested, uncompiled):
You can try more C++ish approach:
If you want to save as binary file, you can use ostream_binary_iterator like this one - http://bit.ly/9JAxdp: