0

I have a .csv file which contains only two columns with names and ages of people. It looks like:

Name      Age
Peter     16
George    15.5
Daniel    18.5

I would only like to collect the ages of the people in a vector of doubles. So I'd like to have something like vect = {16,15.5,18.5}.

How could I achieve this when using only the standard library ?

Many thanks

rado
  • 401
  • 3
  • 8
  • 16
  • 3
    `How could I achieve this?` should be preceded by `what you have done so far` to solve the problem. – sjsam Dec 15 '16 at 14:18
  • 2
    This doesn't look like a CSV file, but rather like a fixed format file? First field starts at offset 0, second field at offset 10? – Elijan9 Dec 15 '16 at 14:34

2 Answers2

2

@BugsFree Thank you for your script but it doesn't seem to work for me.

Here is how I did it eventually (if somebody is interested...)

ifstream infile("myfile.csv");
vector<string> classData;
vector<double> ages;
std::string line;

while (getline(infile, line,'\n'))
{
    classData.push_back(line); //Get each line of the file as a string
}

int s = classData.size();
for (unsigned int i=1; i<s; ++i){
    std::size_t pos = classData[i].find(",");      // position of the end of the name of each one in the respective string
    ages[i-1] = std::stod(classData[i].substr(pos+1,classData[i].size())); // convert string age to a double
}
rado
  • 401
  • 3
  • 8
  • 16
  • Your question *does not* show the data with `,`s. So no one could actually answer with a solution that would work. – crashmstr Dec 16 '16 at 14:06
  • A "csv" file is by definition a comma-separated file so obviously the values are separated by commas as I work on such a file. I simply gave an example of how the data looks like when opened under Microsoft Excel.. – rado Dec 16 '16 at 14:13
  • Yes, and no one has ever been wrong about that. Again, you show your data not as CSV but something that looks like tab separated or fixed width. If your showing of the data and your one mention of CSV don't jive, we either need to ask questions to clarify (not answered for clarified by you) or make guesses about what is really true about your data. – crashmstr Dec 16 '16 at 14:28
0

You can do something like this:

#include <sstream>
#include <string>
#include <fstream>

ifstream infile( "yourfile.csv" ); 
std::vector<double> ages;
while (infile)
{
    std::string line;
    if (!std::getline( infile, line,' ' )) break;
    std::istringstream iss(line);
    string name;
    double age;
    if (!(iss >> name >> age)) { break; }
    ages.push_back(age);
}
BugsFree
  • 540
  • 1
  • 6
  • 24
  • 1
    You should read [this](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – NathanOliver Dec 15 '16 at 14:24