0

I'm a new learner of C++. I have some data saved in Data.csv like this:

     S0001       S0002     S0003   S0004    ...
0   10.289461  17.012874         
1   11.491483  13.053712         
2   10.404887  12.190057          
3   10.502540  16.363996  ...        ...
4   11.102104  12.795502         
5   13.205706  13.707030         
6   10.544555  12.173467         
7   10.380928  12.578932        
...    ...         ...         ...     ...  

I need values column by column to do calculations (column average, moving average, etc), so I want to parse by columns and save them into arrays.

I read these answers but didn't find what I want. What I did is

void read_file(std::vector<std::string>& v, std::string filename){
    std::ifstream inFile(filename);
    std::string temp;
    if (!inFile.is_open()) {
        std::cout<<"Unable to open the file"<<std::endl;
        exit(1);
    }
    while (getline(inFile, temp)) {
        v.push_back(temp);
    }
    inFile.close();
}

int main()
{
    std::string filename = "Book1.csv";
    std::vector<std::string> vec;
    read_file(vec, filename);
    std::cout<<vec[1]<<std::endl;
 }

I can only get values line by line. But how can I parse the file and get values by column?

Cyan
  • 319
  • 2
  • 8
  • [Option 2 in this answer](https://stackoverflow.com/a/7868998/4581301) should get you on the right path. – user4581301 Sep 23 '21 at 17:23
  • Addendum to previous comment: `std::getline` also allows you to set a delimiter to use instead of end of line. This allows you to write stuff like `std::getline(linestream, token, '|');` to split a stream up by the `|` character. – user4581301 Sep 23 '21 at 17:26
  • @user4581301 thank you. Data are seperated by ','. '|' is just for a clear look here to show the data table – Cyan Sep 23 '21 at 17:29
  • 1
    "I read these answers but didn't find what I want." - what about those answers didn't meet your needs? Respectfully, I think you need to knuckle down and try them, then tell us specifically if/where you get stuck. – Tony Delroy Sep 23 '21 at 17:39
  • Always search the internet first. There are a plethora of examples when searching for "C++ read file separated values". – Thomas Matthews Sep 23 '21 at 17:49

1 Answers1

0

You can only read text file line-by-line. If you only need ONE column (unlikely), you could parse that value out of the line and push it into a vector.

If you need to load ALL columns in one pass, create a vector of vectors and push parsed values into a different column vectors.

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27