Reputation: 98
I'm trying to read data from a .tsv file into a vector. The file is structured something like this:
A B
1 2
2 4
6 8
I want to ask what column the program should read, and then push the values from that column into a vector. My code so far is this:
int main() {
string filename, column, headerLine;
vector<double> data, tempData;
int numColumn;
ifstream dataFile;
cout << "enter a filename" << endl;
cin >> filename;
dataFile.open(filename);
cout << "enter a column name" << endl;
cin >> column;
cout << "reading column " << column << " from " << filename;
getline(dataFile, headers);
//here's where I feel stuck
}
If I can get the headers into a vector called headersList and then do something similar for the data rows, I would be able to do this:
for(int i = 0; i < headersList.size(); i++) {
if(headersList[i] == column) {
numColumn = i;
}
}
while(!dataFile.eof()) {
//some way of getting the data points into a vector called tempData
data.push_back(tempData[numColumn]);
tempData.clear();
}
I'd really appreciate some help
Upvotes: 2
Views: 8021
Reputation: 236
Try the following code:
while(!dataFile.eof()) {
std::string str;
std::getline( dataFile, str);
std::stringstream buffer(str);
std::string temp;
std::vector<double> values;
while( getline( buffer, temp, '\t') ) {
values.push_back( ::strtod(temp.c_str(), 0));
}
data.push_back(values[numColumn]);
}
Upvotes: 1