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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With