0

Hello I have 150 data files that have 4 columns in each file. What I am wondering is how would I go about reading that data into a C++ program. I have tried looking online but all the resources I have come across, have only been tutorials on how to input data from one source. The data is also in a sequence to, meaning the text files I'm reading, have the format of "Line_U1.txt", "Line_U2.txt", "Line_U3.txt",... and the data is all consistently as:

column 1 = distances   
column 2 = X_values   
column 3 = Y_values   
column 4 = Z_values   

I would like to import this data into a c++ program, as I have tried with Matlab and I think the data is reading in incorrectly, which is why I am switching to a c++ program but don't know how to read the 150 data files into the program. Any help would be greatly appreciated.

ucMedia
  • 4,105
  • 4
  • 38
  • 46
Robert
  • 153
  • 7

1 Answers1

0

Per this answer, C++17 provides an easy way to get all files in a directory.

#include <string>
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::string path = "/path/to/directory";
    for (auto & filepath : fs::directory_iterator(path))
        read_file(filepath); // You need to define this still
}

As for the actual reading of the file, you should be able to use the tutorials you have already read but for the sake of a complete answer

#include <fstream>

int distances = 0;
int x_values = 0;
int y_values = 0;
int z_values = 0;

void read_file(std::string filepath) {
    /* Might want to do checking here to make sure 
        the file is actually one you want to read in */
    std::ifstream infile(filepath);
    while (infile >> distance >> x >> y >> z) {
        distances += distance;
        x_values += x;
        y_values += y;
        z_values += z;
    }
}

Read more an reading from a file in this answer.