Re: Reading an int array from file.
Compass wrote:
I have an int array in a text file. The file structure is like this:
[1, 2, 3, 4]
[5, 6, 7, 8]
[[1, 2], [3, 4], [5, 6], [7, 8]]
How can I easily read them in to three int arrays?
The third line looks like an array of arrays.
BTW, if it's only the numbers, you could simply
read the file line-by-line and split the line on
'non-numbers'. If you can abstract this out
into a function, your program may look like:
...
typedef std::vector<int> IntVector;
...
int main(int argc, char *argv[])
{
const char *fname = argv[1];
string line;
ifstream fh(fname);
vector<IntVector> vv;
// read the file and split the lines
while( getline(fh, line) )
vv.push_back( split("\\D+", line) );
// print out the arrays on the screen
for(size_t row=0; row<vv.size(); row++) {
for(size_t col=0; col<vv[row].size(); col++)
cout << vv[row][col] << ' ';
cout << endl;
}
return 0;
}
where argv[1] contains the name of your
data file, Your individual arrays (of type
IntVector) will contain the values.
All three arrays are collected in the array
vv (vv[0], vv[1], vv[2]) and are produced by
a function 'split(...)'. This function requires
you to provide a pattern *where* to split the
numbers. In regular-expressionese, this is,
if only Integers are considered, simply a "\D"
(which means: all characters that are no digits).
How would the split function look like? It should
return one IntVector for each line:
IntVector split(const char *pattern, const string& line)
{
IntVector v;
boost::regex num(pattern);
boost::sregex_token_iterator p(line.begin(), line.end(), num, -1), q;
while(p != q) {
string s = (*p++).str();
if(s.length()) v.push_back( atoi(s.c_str()) );
}
return v;
}
and employs the 'sregex_token_iterator' which
extracts values out of the 'delimiters' given in the
pattern. This (its in string form) is then converted
to the desired data type (integer).
The following header files would be needed:
#include <boost/regex.hpp>
#include <fstream>
#include <iostream>
#include <vector>
(plus: using namespace std; here)
(There are myriads of other ways to do that)
Regards
M.