Reputation: 361
I have a file containing values in 15 columns and 1000+ rows.
45285785.00 45285797.00 45285776.00 45285795.00 45285785.00 45285803.00 45285769.00 45285773.00 45285771.00 45285795.00 45285771.00 45285798.00 45285796.00 45285797.00 45285753.00
35497405.00 35497437.00 35497423.00 35497465.00 35497463.00 35497468.00 35497437.00 35497481.00 35497417.00 35497479.00 35497469.00 35497454.00 35497442.00 35497467.00 35497482.00
46598490.00 46598483.00 46598460.00 46598505.00 46598481.00 46598480.00 46598477.00 46598485.00 46598494.00 46598478.00 46598482.00 46598495.00 46598491.00 46598491.00 46598476.00
I want to read this file. The way I'm doing right now is taking 15 variables and then put them into vectors individually.
double col1, col2, ... , col15;
vector <double> C1, C2, ..., C15;
ifstream input('file');
while(input >> col1 >> col2 >> ... >> col15)
{
C1.push_back(col1);
C2.push_back(col2);
...
C15.push_back(col15);
}
Is there a better way to do this? I mean without defining 15 variables, reading 15 columns in the while loop?
Upvotes: 4
Views: 3419
Reputation: 66210
Another "vector or vectors" based example (well... array of vectors in this case).
With while
(so you can check input >> val
result) instead of for
#include <array>
#include <vector>
#include <fstream>
int main ()
{
double val;
std::array<std::vector<double>, 15> C;
std::ifstream input("file");
std::size_t ind { 0 };
while ( input >> val )
{
C[ind++].push_back(val);
if ( ind == C.size() )
ind = 0U;
}
if ( ind != 0U )
; // do something ?
return 0;
}
Upvotes: 1
Reputation: 9908
Yes, There is a better way than what you are doing currently.
You need to declare a 2-D vector of type double
.
vector<vector<double> > C;
for(int i = 0; i < cols.size(); i++) {
input >> cols[i];
C[i].push_back(cols[i]);
}
Upvotes: 1
Reputation: 2783
Yes, there is.
You can consider a container for all of your cols, e.g. vector<double> cols(15)
and also replace your C1, C2 ... C15
variables with vector of vectors. Then you could easily do sth like:
for(int i=0; i<cols.size(); ++i) {
input >> cols[i];
C[i].push_back(cols[i]);
}
However in this case you do not know when you should stop reading. To fix it, you could work with either input.eof()
or input.good()
methods or try to catch fstream >>
operator's return value like you did before in your code.
Upvotes: 6