Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple column and put them in vector in c++

Tags:

c++

c++11

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?

like image 933
MD Abid Hasan Avatar asked Oct 19 '25 03:10

MD Abid Hasan


1 Answers

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.

like image 131
mtszkw Avatar answered Oct 21 '25 17:10

mtszkw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!