Reading multiple columns of data with std::vector

I have a text file with real data points aligned in a column that I am reading into C++ with the attached program. Initially I read it in using a traditional for loop but decided to get a little bit more fancy with the use of the vector class. The code at present is shown below and it works very well for reading in a single column of data. However, my question is, while retaining this same general vector class format, how can I read in multiple columns of data from a .txt or .csv file?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Main program
#include <iostream>
#include "Read_Columnar_File.h"

int main(int argc, const char * argv[]) {
    Read_Columnar_File File1;
    
    char str[20];
    std::strcpy(str,"Test.txt");
    
    File1.Read_File(str);
    
    return 0;
}

// Read_Columnar_File.h
#ifndef __Practice__Read_Columnar_File__
#define __Practice__Read_Columnar_File__

#include <vector>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>

class Read_Columnar_File {
public:
    void Read_File(const std::string& file_name);
};

#endif /* defined(__Practice__Read_Columnar_File__) */

// Read_Columnar_File.cpp
#include "Read_Columnar_File.h"

void Read_Columnar_File::Read_File(const std::string& file_name)
{
    int i;
    std::ifstream inp(file_name,std::ios::in | std::ios::binary);
    if(!inp) {
        std::cout << std::endl << "Cannot Open " << file_name << std::endl;
    }
    std::istream_iterator<float> start((inp)), end;
    std::vector<float> values(start,end);

    for(i=0; i < 7; i++) std::cout << values[i] << std::endl;
    
    inp.close();
}
Depends on what is stored in those columns and how do you want data to be read.
If columns are of different types and rows denotes different entities (like phone book: first column is name, second is phone №), I would create a struct, provide operators >> and << for it and just use your current approach.
Topic archived. No new replies allowed.